<?php
if (!defined('ABSPATH')) {
    exit;
}

if (!function_exists('stakmv_admin_dashboard_parse_ts')) {
    /**
     * Parse auction end-time meta that may be unix timestamp or datetime string.
     *
     * @param mixed $raw Raw meta value.
     * @return int
     */
    function stakmv_admin_dashboard_parse_ts($raw) {
        if (is_numeric($raw)) {
            return (int) $raw;
        }
        if (!is_string($raw) || $raw === '') {
            return 0;
        }
        $ts = strtotime($raw);
        return $ts ? (int) $ts : 0;
    }
}

if (!function_exists('stakmv_admin_dashboard_get_range_window')) {
    /**
     * Build dashboard date window from query-string range.
     *
     * @param string $range Range slug.
     * @return array{range:string,start:int,end:int,label:string}
     */
    function stakmv_admin_dashboard_get_range_window($range) {
        $now   = current_time('timestamp');
        $today = strtotime(date_i18n('Y-m-d 00:00:00', $now), $now);
        $range = sanitize_key((string) $range);

        switch ($range) {
            case 'today':
                $start = $today;
                $label = __('Today', 'stak-multivendor');
                break;
            case '30d':
                $start = strtotime('-29 days', $today);
                $label = __('Last 30 Days', 'stak-multivendor');
                break;
            case 'month':
                $start = strtotime(date_i18n('Y-m-01 00:00:00', $now), $now);
                $label = __('This Month', 'stak-multivendor');
                break;
            case '7d':
            default:
                $range = '7d';
                $start = strtotime('-6 days', $today);
                $label = __('Last 7 Days', 'stak-multivendor');
                break;
        }

        return array(
            'range' => $range,
            'start' => (int) $start,
            'end'   => (int) $now,
            'label' => (string) $label,
        );
    }
}

if (!function_exists('stakmv_admin_dashboard_get_auction_ids')) {
    /**
     * Fetch all auction product IDs used by core.
     *
     * @return int[]
     */
    function stakmv_admin_dashboard_get_auction_ids() {
        // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Admin dashboard aggregate intentionally filters auction product type.
        $ids = get_posts(array(
            'post_type'      => 'product',
            'post_status'    => array('publish', 'pending', 'draft', 'future', 'private'),
            'posts_per_page' => -1,
            'fields'         => 'ids',
            'tax_query'      => array(
                array(
                    'taxonomy' => 'product_type',
                    'field'    => 'slug',
                    'terms'    => array('auction'),
                ),
            ),
        ));
        // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_tax_query

        return array_values(array_map('intval', is_array($ids) ? $ids : array()));
    }
}

if (!function_exists('stakmv_admin_dashboard_get_product_ids')) {
    /**
     * Fetch product IDs used for product-wide marketplace metrics.
     *
     * @return int[]
     */
    function stakmv_admin_dashboard_get_product_ids() {
        $ids = get_posts(array(
            'post_type'      => 'product',
            'post_status'    => array('publish', 'pending', 'draft', 'future', 'private'),
            'posts_per_page' => -1,
            'fields'         => 'ids',
        ));

        return array_values(array_map('intval', is_array($ids) ? $ids : array()));
    }
}

if (!function_exists('stakmv_admin_dashboard_get_commission_rate')) {
    /**
     * Commission rate defaults to 20 only when the option has never been saved.
     *
     * @return float
     */
    function stakmv_admin_dashboard_get_commission_rate() {
        $saved = stakmv_get_option('commission_rate', null);
        $rate = ($saved === null || $saved === false || $saved === '') ? 20.0 : (float) $saved;

        if ($rate < 0) {
            return 0.0;
        }
        if ($rate > 100) {
            return 100.0;
        }

        return $rate;
    }
}

if (!function_exists('stakmv_admin_dashboard_get_sales_metrics')) {
    /**
     * Aggregate sold product quantity and product-line sales for the selected window.
     *
     * @param array $window Time window from stakmv_admin_dashboard_get_range_window().
     * @param float $commission_rate Marketplace commission percentage.
     * @return array{sold_products:int,gross_sales:float,marketplace_earnings:float,vendor_earnings:float}
     */
    function stakmv_admin_dashboard_get_sales_metrics($window, $commission_rate) {
        if (!function_exists('wc_get_orders')) {
            return array(
                'sold_products'         => 0,
                'gross_sales'           => 0.0,
                'marketplace_earnings'  => 0.0,
                'vendor_earnings'       => 0.0,
            );
        }

        $start_ts = (int) ($window['start'] ?? 0);
        $end_ts   = (int) ($window['end'] ?? current_time('timestamp'));
        $orders = wc_get_orders(array(
            'status'       => array('completed', 'processing'),
            'limit'        => -1,
            'orderby'      => 'date',
            'order'        => 'DESC',
            'date_created' => $start_ts . '...' . $end_ts,
        ));

        $sold_products = 0;
        $gross_sales = 0.0;

        foreach ((array) $orders as $order) {
            if (!$order instanceof WC_Order) {
                continue;
            }

            foreach ((array) $order->get_items('line_item') as $item) {
                if (!$item instanceof WC_Order_Item_Product) {
                    continue;
                }

                $product_id = (int) $item->get_product_id();
                if ($product_id <= 0 || get_post_type($product_id) !== 'product') {
                    continue;
                }

                $sold_products += max(0, (int) $item->get_quantity());
                $gross_sales += max(0.0, (float) $item->get_total());
            }
        }

        $marketplace_earnings = round($gross_sales * ((float) $commission_rate / 100), 2);
        $vendor_earnings = max(0.0, $gross_sales - $marketplace_earnings);

        return array(
            'sold_products'         => $sold_products,
            'gross_sales'           => $gross_sales,
            'marketplace_earnings'  => $marketplace_earnings,
            'vendor_earnings'       => $vendor_earnings,
        );
    }
}

if (!function_exists('stakmv_admin_dashboard_get_vendor_ids')) {
    /**
     * Fetch vendor user IDs from core roles.
     *
     * @return int[]
     */
    function stakmv_admin_dashboard_get_vendor_ids() {
        $ids = get_users(array(
            'role__in' => array('stakmv_vendor', 'stakmv_vendor'),
            'fields'   => 'ids',
        ));

        return array_values(array_map('intval', is_array($ids) ? $ids : array()));
    }
}

if (!function_exists('stakmv_admin_dashboard_get_metrics')) {
    /**
     * Build primary dashboard metric payload.
     *
     * @param array $window Time window from stakmv_admin_dashboard_get_range_window().
     * @return array
     */
    function stakmv_admin_dashboard_get_metrics($window) {
        global $wpdb;

        $start_ts = (int) ($window['start'] ?? 0);
        $end_ts   = (int) ($window['end'] ?? 0);
        $now_ts   = current_time('timestamp');

        $auction_ids         = stakmv_admin_dashboard_get_auction_ids();
        $product_ids         = stakmv_admin_dashboard_get_product_ids();
        $commission_rate     = stakmv_admin_dashboard_get_commission_rate();
        $sales_metrics       = stakmv_admin_dashboard_get_sales_metrics($window, $commission_rate);
        $status_counts       = array();
        $active_products     = 0;
        $products_in_range   = 0;
        $created_in_range    = 0;
        $ending_soon         = 0;
        $active_without_bids = 0;

        foreach ($product_ids as $product_id) {
            if (get_post_status($product_id) === 'publish') {
                $active_products++;
            }

            $created_ts = (int) get_post_time('U', false, $product_id);
            if ($created_ts >= $start_ts && $created_ts <= $end_ts) {
                $products_in_range++;
            }
        }

        foreach ($auction_ids as $auction_id) {
            $status = sanitize_key((string) get_post_meta($auction_id, '_stakmv_auction_status', true));
            if ($status === '') {
                $status = 'active';
            }

            if (!isset($status_counts[$status])) {
                $status_counts[$status] = 0;
            }
            $status_counts[$status]++;

            $created_ts = (int) get_post_time('U', false, $auction_id);
            if ($created_ts >= $start_ts && $created_ts <= $end_ts) {
                $created_in_range++;
            }

            $end_raw = get_post_meta($auction_id, '_stakmv_auction_end_time', true);
            $end_ts_item = stakmv_admin_dashboard_parse_ts($end_raw);
            if ($end_ts_item > $now_ts && $end_ts_item <= ($now_ts + DAY_IN_SECONDS) && $status === 'active') {
                $ending_soon++;
            }

            if ($status === 'active') {
                $bid_count = (int) get_post_meta($auction_id, '_stakmv_auction_bid_count', true);
                if ($bid_count <= 0) {
                    $active_without_bids++;
                }
            }
        }

        $bids_table = esc_sql(defined('STAKMV_AUCTION_BIDS_TABLE') ? STAKMV_AUCTION_BIDS_TABLE : ($wpdb->prefix . 'stakmv_auction_bids'));
        $total_bids = 0;
        $bids_range = 0;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Plugin-owned bids table existence check.
        $bids_table_exists = ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $bids_table)) === $bids_table);
        if ($bids_table_exists) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Aggregate over plugin-owned bids table.
            $total_bids = (int) $wpdb->get_var(
                $wpdb->prepare(
                    'SELECT COUNT(*) FROM %i',
                    $bids_table
                )
            );

            $start_mysql = gmdate('Y-m-d H:i:s', $start_ts);
            $end_mysql   = gmdate('Y-m-d H:i:s', $end_ts);
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Bounded aggregate for selected window.
            $bids_range = (int) $wpdb->get_var(
                $wpdb->prepare(
                    'SELECT COUNT(*) FROM %i WHERE created_at >= %s AND created_at <= %s',
                    $bids_table,
                    $start_mysql,
                    $end_mysql
                )
            );
        }

        $vendor_ids       = stakmv_admin_dashboard_get_vendor_ids();
        $active_vendors   = 0;
        $new_vendors      = 0;
        $pending_apps     = 0;
        foreach ($vendor_ids as $vendor_id) {
            if (get_user_meta($vendor_id, 'stakmv_vendor_suspended', true) !== 'yes') {
                $active_vendors++;
            }
            $vendor_user = get_userdata($vendor_id);
            if (!$vendor_user instanceof WP_User) {
                continue;
            }
            $registered_ts = strtotime((string) $vendor_user->user_registered);
            if ($registered_ts && $registered_ts >= $start_ts && $registered_ts <= $end_ts) {
                $new_vendors++;
            }
        }

        // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Dashboard alert card needs vendor application status meta.
        $application_users = get_users(array(
            'meta_key' => '_stakmv_vendor_application',
            'fields'   => 'ids',
        ));
        // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key
        foreach ((array) $application_users as $user_id) {
            $app = get_user_meta((int) $user_id, '_stakmv_vendor_application', true);
            if (is_array($app) && (($app['status'] ?? '') === 'pending')) {
                $pending_apps++;
            }
        }

        $pending_escrows = function_exists('stakmv_get_pending_escrows') ? count((array) stakmv_get_pending_escrows()) : 0;

        return array(
            'auction_ids'         => $auction_ids,
            'product_ids'         => $product_ids,
            'total_products'      => count($product_ids),
            'active_products'     => $active_products,
            'sold_products'       => (int) $sales_metrics['sold_products'],
            'products_in_range'   => $products_in_range,
            'total_auctions'      => count($auction_ids),
            'active_auctions'     => (int) ($status_counts['active'] ?? 0),
            'sold_auctions'       => (int) ($status_counts['sold'] ?? 0),
            'gross_sales'         => (float) $sales_metrics['gross_sales'],
            'marketplace_earnings'=> (float) $sales_metrics['marketplace_earnings'],
            'vendor_earnings'     => (float) $sales_metrics['vendor_earnings'],
            'commission_rate'     => $commission_rate,
            'status_counts'       => $status_counts,
            'created_in_range'    => $created_in_range,
            'ending_soon'         => $ending_soon,
            'active_without_bids' => $active_without_bids,
            'total_bids'          => $total_bids,
            'bids_in_range'       => $bids_range,
            'active_vendors'      => $active_vendors,
            'new_vendors'         => $new_vendors,
            'pending_apps'        => $pending_apps,
            'pending_escrows'     => (int) $pending_escrows,
            'bids_table_exists'   => (bool) $bids_table_exists,
            'bids_table'          => $bids_table,
        );
    }
}

if (!function_exists('stakmv_admin_dashboard_get_recent_bids')) {
    /**
     * Fetch recent bids for dashboard table.
     *
     * @param array $window Time window.
     * @param array $metrics Metrics payload.
     * @return array<int, array<string,mixed>>
     */
    function stakmv_admin_dashboard_get_recent_bids($window, $metrics) {
        global $wpdb;

        if (empty($metrics['bids_table_exists']) || empty($metrics['bids_table'])) {
            return array();
        }

        $start_mysql = gmdate('Y-m-d H:i:s', (int) $window['start']);
        $end_mysql   = gmdate('Y-m-d H:i:s', (int) $window['end']);
        $bids_table  = esc_sql((string) $metrics['bids_table']);

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Read-only dashboard list over plugin-owned bids table.
        $rows = $wpdb->get_results(
            $wpdb->prepare(
                'SELECT b.auction_id, b.user_id, b.bid_amount, b.created_at, p.post_title, u.display_name
                 FROM %i b
                 LEFT JOIN %i p ON p.ID = b.auction_id
                 LEFT JOIN %i u ON u.ID = b.user_id
                 WHERE b.created_at >= %s AND b.created_at <= %s
                 ORDER BY b.created_at DESC
                 LIMIT 12',
                $bids_table,
                $wpdb->posts,
                $wpdb->users,
                $start_mysql,
                $end_mysql
            ),
            ARRAY_A
        );

        return is_array($rows) ? $rows : array();
    }
}

if (!function_exists('stakmv_admin_dashboard_get_top_auctions')) {
    /**
     * Fetch top auctions by bid volume for the selected time window.
     *
     * @param array $window Time window.
     * @param array $metrics Metrics payload.
     * @return array<int, array<string,mixed>>
     */
    function stakmv_admin_dashboard_get_top_auctions($window, $metrics) {
        global $wpdb;

        if (empty($metrics['bids_table_exists']) || empty($metrics['bids_table'])) {
            return array();
        }

        $start_mysql = gmdate('Y-m-d H:i:s', (int) $window['start']);
        $end_mysql   = gmdate('Y-m-d H:i:s', (int) $window['end']);
        $bids_table  = esc_sql((string) $metrics['bids_table']);

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Read-only aggregate over plugin-owned bids table.
        $rows = $wpdb->get_results(
            $wpdb->prepare(
                'SELECT b.auction_id, COUNT(*) AS bids_count, MAX(b.bid_amount) AS highest_bid, p.post_title
                 FROM %i b
                 LEFT JOIN %i p ON p.ID = b.auction_id
                 WHERE b.created_at >= %s AND b.created_at <= %s
                 GROUP BY b.auction_id
                 ORDER BY bids_count DESC, highest_bid DESC
                 LIMIT 8',
                $bids_table,
                $wpdb->posts,
                $start_mysql,
                $end_mysql
            ),
            ARRAY_A
        );

        return is_array($rows) ? $rows : array();
    }
}

if (!function_exists('stakmv_admin_dashboard_get_ending_soon_rows')) {
    /**
     * Build ending soon rows from core auction data.
     *
     * @param int[] $auction_ids Auction IDs.
     * @return array<int, array<string,mixed>>
     */
    function stakmv_admin_dashboard_get_ending_soon_rows($auction_ids) {
        $rows   = array();
        $now_ts = current_time('timestamp');
        $limit  = 8;

        foreach ((array) $auction_ids as $auction_id) {
            $auction_id = (int) $auction_id;
            if ($auction_id <= 0) {
                continue;
            }

            $status = sanitize_key((string) get_post_meta($auction_id, '_stakmv_auction_status', true));
            if ($status === '') {
                $status = 'active';
            }
            if ($status !== 'active') {
                continue;
            }

            $end_raw = get_post_meta($auction_id, '_stakmv_auction_end_time', true);
            $end_ts  = stakmv_admin_dashboard_parse_ts($end_raw);
            if ($end_ts <= $now_ts || $end_ts > ($now_ts + DAY_IN_SECONDS)) {
                continue;
            }

            $vendor_id = (int) get_post_field('post_author', $auction_id);
            $vendor_name = (string) get_the_author_meta('display_name', $vendor_id);
            $current_bid = function_exists('stakmv_get_highest_bid') ? (float) stakmv_get_highest_bid($auction_id) : 0.0;

            $rows[] = array(
                'auction_id'   => $auction_id,
                'title'        => get_the_title($auction_id),
                'vendor_name'  => $vendor_name !== '' ? $vendor_name : ('User #' . $vendor_id),
                'current_bid'  => $current_bid,
                'end_ts'       => $end_ts,
                'status'       => $status,
            );
        }

        usort($rows, static function ($a, $b) {
            return (int) $a['end_ts'] <=> (int) $b['end_ts'];
        });

        return array_slice($rows, 0, $limit);
    }
}

if (!function_exists('stakmv_admin_dashboard_get_activity_rows')) {
    /**
     * Build 7-day activity rows for created products and placed bids.
     *
     * @param int[] $product_ids Product IDs.
     * @param array $metrics Metrics payload.
     * @return array<int, array<string,mixed>>
     */
    function stakmv_admin_dashboard_get_activity_rows($product_ids, $metrics) {
        global $wpdb;

        $rows = array();
        $today_midnight = strtotime(date_i18n('Y-m-d 00:00:00', current_time('timestamp')), current_time('timestamp'));
        for ($i = 6; $i >= 0; $i--) {
            $ts = strtotime("-{$i} days", $today_midnight);
            $key = gmdate('Y-m-d', $ts);
            $rows[$key] = array(
                'day_key'          => $key,
                'label'            => date_i18n('d M', $ts),
                'products_created' => 0,
                'bids_placed'      => 0,
            );
        }

        foreach ((array) $product_ids as $product_id) {
            $product_id = (int) $product_id;
            if ($product_id <= 0) {
                continue;
            }
            $created_ts = (int) get_post_time('U', false, $product_id);
            $day_key = gmdate('Y-m-d', $created_ts);
            if (isset($rows[$day_key])) {
                $rows[$day_key]['products_created']++;
            }
        }

        if (!empty($metrics['bids_table_exists']) && !empty($metrics['bids_table'])) {
            $bids_table = esc_sql((string) $metrics['bids_table']);
            $start_mysql = gmdate('Y-m-d 00:00:00', strtotime('-6 days', $today_midnight));

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Read-only grouped trend query over plugin-owned bids table.
            $bid_rows = $wpdb->get_results(
                $wpdb->prepare(
                    'SELECT DATE(created_at) AS day_key, COUNT(*) AS total
                     FROM %i
                     WHERE created_at >= %s
                     GROUP BY DATE(created_at)
                     ORDER BY day_key ASC',
                    $bids_table,
                    $start_mysql
                ),
                ARRAY_A
            );

            foreach ((array) $bid_rows as $bid_row) {
                $day_key = sanitize_text_field((string) ($bid_row['day_key'] ?? ''));
                if ($day_key !== '' && isset($rows[$day_key])) {
                    $rows[$day_key]['bids_placed'] = (int) ($bid_row['total'] ?? 0);
                }
            }
        }

        return array_values($rows);
    }
}

add_action('stakmv_auctions_render_tab_dashboard', function () {
    if (!current_user_can('manage_woocommerce')) {
        echo '<p>' . esc_html__('Insufficient permissions.', 'stak-multivendor') . '</p>';
        return;
    }

    $range = '7d';
    $range_nonce = filter_input(INPUT_GET, 'stakmv_dashboard_range_nonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    if ($range_nonce && wp_verify_nonce(sanitize_text_field((string) $range_nonce), 'stakmv_dashboard_range')) {
        $range_raw = filter_input(INPUT_GET, 'range', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        $range = sanitize_key((string) ($range_raw ?: '7d'));
    }
    $window = stakmv_admin_dashboard_get_range_window($range);
    $metrics = stakmv_admin_dashboard_get_metrics($window);
    $ending_soon_rows = stakmv_admin_dashboard_get_ending_soon_rows($metrics['auction_ids']);
    $recent_bids = stakmv_admin_dashboard_get_recent_bids($window, $metrics);
    $top_auctions = stakmv_admin_dashboard_get_top_auctions($window, $metrics);
    $activity_rows = stakmv_admin_dashboard_get_activity_rows($metrics['product_ids'], $metrics);

    $max_activity = 1;
    foreach ($activity_rows as $row) {
        $max_activity = max($max_activity, (int) $row['products_created'], (int) $row['bids_placed']);
    }

    $management_nonce = wp_create_nonce('stakmv_management_sub');
    $products_url = add_query_arg(
        array('page' => 'stakmv-auctions', 'tab' => 'management', 'sub' => 'products', 'stakmv_management_sub_nonce' => $management_nonce),
        admin_url('admin.php')
    );
    $vendors_url = add_query_arg(
        array('page' => 'stakmv-auctions', 'tab' => 'management', 'sub' => 'vendors', 'stakmv_management_sub_nonce' => $management_nonce),
        admin_url('admin.php')
    );
    $escrows_url = add_query_arg(
        array('page' => 'stakmv-auctions', 'tab' => 'management', 'sub' => 'escrows', 'stakmv_management_sub_nonce' => $management_nonce),
        admin_url('admin.php')
    );
    $applications_url = admin_url('admin.php?page=stakmv-auctions&tab=vendors');
    ?>
    <div class="wcmv-admin-dashboard">
        <div class="wcmv-admin-dashboard-head">
            <div>
                <h2><?php esc_html_e('at a glance:', 'stak-multivendor'); ?></h2>
            </div>
            <form method="get" class="wcmv-admin-dashboard-filters">
                <input type="hidden" name="page" value="stakmv-auctions">
                <input type="hidden" name="tab" value="dashboard">
                <?php wp_nonce_field('stakmv_dashboard_range', 'stakmv_dashboard_range_nonce'); ?>
                <label for="wcmv-dashboard-range" class="screen-reader-text"><?php esc_html_e('Time Range', 'stak-multivendor'); ?></label>
                <select id="wcmv-dashboard-range" name="range">
                    <option value="today" <?php selected($window['range'], 'today'); ?>><?php esc_html_e('Today', 'stak-multivendor'); ?></option>
                    <option value="7d" <?php selected($window['range'], '7d'); ?>><?php esc_html_e('7 days', 'stak-multivendor'); ?></option>
                    <option value="30d" <?php selected($window['range'], '30d'); ?>><?php esc_html_e('30 days', 'stak-multivendor'); ?></option>
                    <option value="month" <?php selected($window['range'], 'month'); ?>><?php esc_html_e('This month', 'stak-multivendor'); ?></option>
                </select>
                <button type="submit" class="button"><?php esc_html_e('Refresh', 'stak-multivendor'); ?></button>
            </form>
        </div>

        <div class="wcmv-admin-kpis">
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url($products_url); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Total Products', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo esc_html(number_format_i18n((int) $metrics['total_products'])); ?></strong>
                <?php /* translators: 1: number of products, 2: selected date range label. */ ?>
                <span class="wcmv-admin-kpi-meta"><?php echo esc_html(sprintf(__('%1$d created in %2$s', 'stak-multivendor'), (int) $metrics['products_in_range'], (string) $window['label'])); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url($products_url); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Active Products', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo esc_html(number_format_i18n((int) $metrics['active_products'])); ?></strong>
                <span class="wcmv-admin-kpi-meta"><?php esc_html_e('Published product count', 'stak-multivendor'); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url($products_url); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Ending Auctions in 24h', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo esc_html(number_format_i18n((int) $metrics['ending_soon'])); ?></strong>
                <span class="wcmv-admin-kpi-meta"><?php esc_html_e('Needs immediate attention', 'stak-multivendor'); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url($products_url); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Sold Products', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo esc_html(number_format_i18n((int) $metrics['sold_products'])); ?></strong>
                <?php /* translators: %s: selected date range label. */ ?>
                <span class="wcmv-admin-kpi-meta"><?php echo esc_html(sprintf(__('Sold in %s', 'stak-multivendor'), (string) $window['label'])); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url($products_url); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Gross Sales', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo function_exists('wc_price') ? wp_kses_post(wc_price((float) $metrics['gross_sales'])) : esc_html(number_format_i18n((float) $metrics['gross_sales'], 2)); ?></strong>
                <?php /* translators: %s: selected date range label. */ ?>
                <span class="wcmv-admin-kpi-meta"><?php echo esc_html(sprintf(__('Product sales in %s', 'stak-multivendor'), (string) $window['label'])); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url(admin_url('admin.php?page=stakmv-auctions&tab=general')); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Marketplace Earnings', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo function_exists('wc_price') ? wp_kses_post(wc_price((float) $metrics['marketplace_earnings'])) : esc_html(number_format_i18n((float) $metrics['marketplace_earnings'], 2)); ?></strong>
                <?php /* translators: %s: commission percentage. */ ?>
                <span class="wcmv-admin-kpi-meta"><?php echo esc_html(sprintf(__('%s%% commission rate', 'stak-multivendor'), number_format_i18n((float) $metrics['commission_rate'], 2))); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url($escrows_url); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Vendor Earnings', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo function_exists('wc_price') ? wp_kses_post(wc_price((float) $metrics['vendor_earnings'])) : esc_html(number_format_i18n((float) $metrics['vendor_earnings'], 2)); ?></strong>
                <?php /* translators: %s: selected date range label. */ ?>
                <span class="wcmv-admin-kpi-meta"><?php echo esc_html(sprintf(__('Estimated payouts in %s', 'stak-multivendor'), (string) $window['label'])); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url($products_url); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Total Auctions', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo esc_html(number_format_i18n((int) $metrics['total_auctions'])); ?></strong>
                <?php /* translators: 1: number of auctions, 2: selected date range label. */ ?>
                <span class="wcmv-admin-kpi-meta"><?php echo esc_html(sprintf(__('%1$d auctions created in %2$s', 'stak-multivendor'), (int) $metrics['created_in_range'], (string) $window['label'])); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url($products_url); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Active Auctions', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo esc_html(number_format_i18n((int) $metrics['active_auctions'])); ?></strong>
                <?php /* translators: %d: number of active auctions with zero bids. */ ?>
                <span class="wcmv-admin-kpi-meta"><?php echo esc_html(sprintf(__('%d with no bids yet', 'stak-multivendor'), (int) $metrics['active_without_bids'])); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url('#wcmv-recent-bids'); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Total Bids', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo esc_html(number_format_i18n((int) $metrics['total_bids'])); ?></strong>
                <?php /* translators: 1: number of bids, 2: selected date range label. */ ?>
                <span class="wcmv-admin-kpi-meta"><?php echo esc_html(sprintf(__('%1$d bids in %2$s', 'stak-multivendor'), (int) $metrics['bids_in_range'], (string) $window['label'])); ?></span>
            </a>
            <a class="wcmv-admin-kpi-card" href="<?php echo esc_url($vendors_url); ?>">
                <span class="wcmv-admin-kpi-label"><?php esc_html_e('Active Vendors', 'stak-multivendor'); ?></span>
                <strong class="wcmv-admin-kpi-value"><?php echo esc_html(number_format_i18n((int) $metrics['active_vendors'])); ?></strong>
                <?php /* translators: 1: number of vendors, 2: selected date range label. */ ?>
                <span class="wcmv-admin-kpi-meta"><?php echo esc_html(sprintf(__('%1$d new vendors in %2$s', 'stak-multivendor'), (int) $metrics['new_vendors'], (string) $window['label'])); ?></span>
            </a>
        </div>

        <div class="wcmv-admin-dashboard-grid">
            <section class="wcmv-admin-card wcmv-admin-card-wide">
                <h3><?php esc_html_e('Activity Snapshot (Last 7 Days)', 'stak-multivendor'); ?></h3>
                <table class="widefat striped wcmv-admin-activity-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Day', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Products Created', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Bids Placed', 'stak-multivendor'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($activity_rows as $row) : ?>
                        <?php
                        $created_count = (int) $row['products_created'];
                        $bids_count = (int) $row['bids_placed'];
                        $created_width = max(4, (int) round(($created_count / $max_activity) * 100));
                        $bids_width = max(4, (int) round(($bids_count / $max_activity) * 100));
                        ?>
                        <tr>
                            <td><?php echo esc_html((string) $row['label']); ?></td>
                            <td>
                                <span class="wcmv-admin-inline-metric"><?php echo esc_html((string) $created_count); ?></span>
                                <span class="wcmv-admin-mini-bar wcmv-admin-mini-bar-created" style="width:<?php echo esc_attr((string) $created_width); ?>%"></span>
                            </td>
                            <td>
                                <span class="wcmv-admin-inline-metric"><?php echo esc_html((string) $bids_count); ?></span>
                                <span class="wcmv-admin-mini-bar wcmv-admin-mini-bar-bids" style="width:<?php echo esc_attr((string) $bids_width); ?>%"></span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </section>

            <section class="wcmv-admin-card">
                <h3><?php esc_html_e('Auction Status Breakdown', 'stak-multivendor'); ?></h3>
                <ul class="wcmv-admin-status-list">
                    <?php
                    $status_labels = array(
                        'active'          => __('Active', 'stak-multivendor'),
                        'pending_payment' => __('Pending Payment', 'stak-multivendor'),
                        'ended'           => __('Ended', 'stak-multivendor'),
                        'sold'            => __('Sold', 'stak-multivendor'),
                        'expired'         => __('Expired', 'stak-multivendor'),
                    );
                    foreach ($status_labels as $key => $label) :
                        ?>
                        <li>
                            <span><?php echo esc_html($label); ?></span>
                            <strong><?php echo esc_html(number_format_i18n((int) ($metrics['status_counts'][$key] ?? 0))); ?></strong>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </section>

            <section class="wcmv-admin-card">
                <h3><?php esc_html_e('Alerts', 'stak-multivendor'); ?></h3>
                <ul class="wcmv-admin-alert-list">
                    <li>
                        <span><?php esc_html_e('Active auctions with zero bids', 'stak-multivendor'); ?></span>
                        <strong><?php echo esc_html(number_format_i18n((int) $metrics['active_without_bids'])); ?></strong>
                    </li>
                    <li>
                        <span><?php esc_html_e('Pending escrows', 'stak-multivendor'); ?></span>
                        <strong><?php echo esc_html(number_format_i18n((int) $metrics['pending_escrows'])); ?></strong>
                    </li>
                    <li>
                        <span><?php esc_html_e('Pending vendor applications', 'stak-multivendor'); ?></span>
                        <strong><?php echo esc_html(number_format_i18n((int) $metrics['pending_apps'])); ?></strong>
                    </li>
                </ul>
            </section>

            <section class="wcmv-admin-card">
                <h3><?php esc_html_e('Quick Actions', 'stak-multivendor'); ?></h3>
                <div class="wcmv-admin-quick-actions">
                    <a class="button" href="<?php echo esc_url($products_url); ?>"><?php esc_html_e('Manage Products', 'stak-multivendor'); ?></a>
                    <a class="button" href="<?php echo esc_url($vendors_url); ?>"><?php esc_html_e('Manage Vendors', 'stak-multivendor'); ?></a>
                    <a class="button" href="<?php echo esc_url($escrows_url); ?>"><?php esc_html_e('Review Escrows', 'stak-multivendor'); ?></a>
                    <a class="button" href="<?php echo esc_url($applications_url); ?>"><?php esc_html_e('Vendor Applications', 'stak-multivendor'); ?></a>
                    <a class="button" href="<?php echo esc_url(admin_url('admin.php?page=stakmv-auctions&tab=general')); ?>"><?php esc_html_e('General Settings', 'stak-multivendor'); ?></a>
                </div>
            </section>
        </div>

        <section class="wcmv-admin-card">
            <h3><?php esc_html_e('Ending Soon (Next 24 Hours)', 'stak-multivendor'); ?></h3>
            <?php if (empty($ending_soon_rows)) : ?>
                <p><?php esc_html_e('No active auctions ending in the next 24 hours.', 'stak-multivendor'); ?></p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Product', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Vendor', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Current Bid', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Ends', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Status', 'stak-multivendor'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($ending_soon_rows as $row) : ?>
                        <tr>
                            <td>
                                <a href="<?php echo esc_url(admin_url('post.php?post=' . (int) $row['auction_id'] . '&action=edit')); ?>">
                                    <?php echo esc_html((string) ($row['title'] ?: ('Auction #' . (int) $row['auction_id']))); ?>
                                </a>
                            </td>
                            <td><?php echo esc_html((string) $row['vendor_name']); ?></td>
                            <td>
                                <?php
                                $current_bid = (float) $row['current_bid'];
                                echo function_exists('wc_price')
                                    ? wp_kses_post(wc_price($current_bid))
                                    : esc_html(number_format_i18n($current_bid, 2));
                                ?>
                            </td>
                            <td><?php echo esc_html(date_i18n('d M Y H:i', (int) $row['end_ts'])); ?></td>
                            <td><?php echo esc_html(ucfirst((string) $row['status'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>

        <section class="wcmv-admin-card" id="wcmv-recent-bids">
            <?php /* translators: %s: selected date range label. */ ?>
            <h3><?php echo esc_html(sprintf(__('Recent Bids (%s)', 'stak-multivendor'), (string) $window['label'])); ?></h3>
            <?php if (empty($recent_bids)) : ?>
                <p><?php esc_html_e('No bids found for the selected range.', 'stak-multivendor'); ?></p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Product', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Bidder', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Amount', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Time', 'stak-multivendor'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($recent_bids as $row) : ?>
                        <?php $auction_id = (int) ($row['auction_id'] ?? 0); ?>
                        <tr>
                            <td>
                                <?php if ($auction_id > 0) : ?>
                                    <a href="<?php echo esc_url(admin_url('post.php?post=' . $auction_id . '&action=edit')); ?>">
                                        <?php echo esc_html((string) (($row['post_title'] ?? '') !== '' ? $row['post_title'] : ('Auction #' . $auction_id))); ?>
                                    </a>
                                <?php else : ?>
                                    <?php esc_html_e('Unknown product', 'stak-multivendor'); ?>
                                <?php endif; ?>
                            </td>
                            <td><?php echo esc_html((string) (($row['display_name'] ?? '') !== '' ? $row['display_name'] : ('User #' . (int) ($row['user_id'] ?? 0)))); ?></td>
                            <td>
                                <?php
                                $amount = (float) ($row['bid_amount'] ?? 0);
                                echo function_exists('wc_price')
                                    ? wp_kses_post(wc_price($amount))
                                    : esc_html(number_format_i18n($amount, 2));
                                ?>
                            </td>
                            <td>
                                <?php
                                $created_ts = strtotime((string) ($row['created_at'] ?? ''));
                                echo $created_ts
                                    ? esc_html(date_i18n('d M Y H:i', $created_ts))
                                    : '—';
                                ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>

        <section class="wcmv-admin-card">
            <?php /* translators: %s: selected date range label. */ ?>
            <h3><?php echo esc_html(sprintf(__('Top Auction Products by Bid Volume (%s)', 'stak-multivendor'), (string) $window['label'])); ?></h3>
            <?php if (empty($top_auctions)) : ?>
                <p><?php esc_html_e('Not enough bid data for this period yet.', 'stak-multivendor'); ?></p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Product', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Bids', 'stak-multivendor'); ?></th>
                            <th><?php esc_html_e('Highest Bid', 'stak-multivendor'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($top_auctions as $row) : ?>
                        <?php $auction_id = (int) ($row['auction_id'] ?? 0); ?>
                        <tr>
                            <td>
                                <?php if ($auction_id > 0) : ?>
                                    <a href="<?php echo esc_url(admin_url('post.php?post=' . $auction_id . '&action=edit')); ?>">
                                        <?php echo esc_html((string) (($row['post_title'] ?? '') !== '' ? $row['post_title'] : ('Auction #' . $auction_id))); ?>
                                    </a>
                                <?php else : ?>
                                    <?php esc_html_e('Unknown product', 'stak-multivendor'); ?>
                                <?php endif; ?>
                            </td>
                            <td><?php echo esc_html(number_format_i18n((int) ($row['bids_count'] ?? 0))); ?></td>
                            <td>
                                <?php
                                $highest = (float) ($row['highest_bid'] ?? 0);
                                echo function_exists('wc_price')
                                    ? wp_kses_post(wc_price($highest))
                                    : esc_html(number_format_i18n($highest, 2));
                                ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </section>
    </div>
    <?php
});
