<?php

namespace Calio\Admin\DashboardWidgets;

use Calio\Support\Settings;

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

/**
 * Provides a lightweight executive summary of recent customer geography and acquisition.
 */
final class MarketingIntelligenceHud
{
    private const CACHE_KEY = 'calio_marketing_intelligence_hud_v1';
    private const CACHE_TTL = 15 * MINUTE_IN_SECONDS;
    private const DASHBOARD_SLUG = 'marketing-intelligence-hud';
    private const SCRIPT_HANDLE = 'calio-marketing-intelligence-hud';

    public function __construct()
    {
        add_action('wp_dashboard_setup', [$this, 'register']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
    }

    public function register(): void
    {
        if (
            !Settings::is_dashboard_widget_enabled(self::DASHBOARD_SLUG)
            || !$this->can_view()
        ) {
            return;
        }

        wp_add_dashboard_widget(
            'calio_marketing_intelligence_hud',
            esc_html__('Marketing Intelligence HUD', 'calio-addon'),
            [$this, 'render'],
            null,
            null,
            'normal',
            'core'
        );
    }

    public function enqueue_assets(string $hook_suffix): void
    {
        if (
            $hook_suffix !== 'index.php'
            || !Settings::is_dashboard_widget_enabled(self::DASHBOARD_SLUG)
            || !$this->can_view()
        ) {
            return;
        }

        wp_enqueue_style(
            'calio-dashboard-widget',
            CALIO_URL . 'assets/admin/dashboard-widget.css',
            ['dashicons'],
            CALIO_VERSION
        );
        wp_enqueue_script(
            self::SCRIPT_HANDLE,
            CALIO_URL . 'assets/admin/marketing-intelligence-hud.js',
            [],
            CALIO_VERSION,
            true
        );
        wp_localize_script(
            self::SCRIPT_HANDLE,
            'calioMarketingHud',
            [
                'filePrefix' => 'calio-marketing-intelligence',
                'labels' => [
                    'geography' => __('Geography', 'calio-addon'),
                    'traffic' => __('Traffic Sources', 'calio-addon'),
                    'location' => __('Location', 'calio-addon'),
                    'source' => __('Traffic Source', 'calio-addon'),
                    'orders' => __('Orders', 'calio-addon'),
                    'revenue' => __('Revenue', 'calio-addon'),
                    'empty' => __('There is no data to export.', 'calio-addon'),
                ],
            ]
        );
    }

    public function render(): void
    {
        if (!$this->can_view()) {
            return;
        }

        if (!function_exists('wc_get_orders')) {
            echo '<div class="calio-marketing-hud__notice">';
            echo '<p>' . esc_html__('WooCommerce must be installed and active to display marketing intelligence.', 'calio-addon') . '</p>';
            echo '</div>';
            return;
        }

        $data = $this->report_data();

        echo '<div class="calio-marketing-hud" data-calio-marketing-hud>';
        echo '<div class="calio-marketing-hud__summary">';
        echo '<div>';
        echo '<span>' . esc_html__('Recent sample', 'calio-addon') . '</span>';
        echo '<strong>' . esc_html(
            sprintf(
                /* translators: %d: number of analyzed orders. */
                _n('%d order', '%d orders', $data['order_count'], 'calio-addon'),
                $data['order_count']
            )
        ) . '</strong>';
        echo '</div>';
        echo '<div>';
        echo '<span>' . esc_html__('Analyzed revenue', 'calio-addon') . '</span>';
        echo '<strong>' . esc_html(wp_strip_all_tags(wc_price($data['total_revenue']))) . '</strong>';
        echo '</div>';
        echo '<small>' . esc_html(
            sprintf(
                /* translators: %s: cache generation time. */
                __('Updated %s · cached 15 minutes', 'calio-addon'),
                $data['generated_at']
            )
        ) . '</small>';
        echo '</div>';

        echo '<div class="calio-marketing-hud__toolbar">';
        echo '<div class="calio-marketing-hud__tabs" role="tablist" aria-label="' . esc_attr__('Marketing intelligence views', 'calio-addon') . '">';
        echo '<button type="button" class="is-active" role="tab" aria-selected="true" data-marketing-tab="geography">' . esc_html__('Geography', 'calio-addon') . '</button>';
        echo '<button type="button" role="tab" aria-selected="false" data-marketing-tab="traffic">' . esc_html__('Traffic Sources', 'calio-addon') . '</button>';
        echo '</div>';
        echo '<button type="button" class="button button-primary" data-marketing-export>';
        echo esc_html__('Export CSV', 'calio-addon');
        echo '</button>';
        echo '</div>';

        echo '<div class="calio-marketing-hud__panel is-active" role="tabpanel" data-marketing-panel="geography">';
        echo '<div class="calio-marketing-hud__geo-grid">';
        $this->render_ranked_list(
            __('Top 5 Cities', 'calio-addon'),
            $data['cities'],
            'city'
        );
        $this->render_ranked_list(
            __('Top 3 Countries', 'calio-addon'),
            $data['countries'],
            'country'
        );
        echo '</div>';
        echo '</div>';

        echo '<div class="calio-marketing-hud__panel" role="tabpanel" data-marketing-panel="traffic" hidden>';
        $this->render_ranked_list(
            __('Traffic Source Revenue', 'calio-addon'),
            $data['sources'],
            'source'
        );
        echo '</div>';
        echo '<p class="calio-marketing-hud__status" data-marketing-status aria-live="polite"></p>';
        echo '</div>';
    }

    /**
     * @return array{
     *     cities: array<int, array{name: string, orders: int, revenue: float}>,
     *     countries: array<int, array{name: string, orders: int, revenue: float}>,
     *     sources: array<int, array{name: string, orders: int, revenue: float}>,
     *     order_count: int,
     *     total_revenue: float,
     *     generated_at: string
     * }
     */
    private function report_data(): array
    {
        $cached = get_transient(self::CACHE_KEY);
        if (
            is_array($cached)
            && isset($cached['cities'], $cached['countries'], $cached['sources'], $cached['order_count'], $cached['total_revenue'], $cached['generated_at'])
        ) {
            return $cached;
        }

        $cities = [];
        $countries = [];
        $sources = [];
        $total_revenue = 0.0;
        $orders = wc_get_orders(
            [
                'limit' => 25,
                'status' => array_keys(wc_get_order_statuses()),
                'orderby' => 'date',
                'order' => 'DESC',
                'return' => 'objects',
            ]
        );

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

            $revenue = (float) $order->get_total();
            $total_revenue += $revenue;
            $city = sanitize_text_field((string) $order->get_billing_city());
            $country_code = sanitize_key((string) $order->get_billing_country());
            $country = $this->country_name($country_code);
            $source = $this->traffic_source($order);

            $this->add_metric($cities, $city !== '' ? $city : __('Unknown city', 'calio-addon'), $revenue);
            $this->add_metric($countries, $country, $revenue);
            $this->add_metric($sources, $source, $revenue);
        }

        $data = [
            'cities' => $this->rank_metrics($cities, 5),
            'countries' => $this->rank_metrics($countries, 3),
            'sources' => $this->rank_metrics($sources, 0),
            'order_count' => count($orders),
            'total_revenue' => $total_revenue,
            'generated_at' => wp_date(get_option('time_format')),
        ];

        set_transient(self::CACHE_KEY, $data, self::CACHE_TTL);
        return $data;
    }

    /**
     * @param array<string, array{orders: int, revenue: float}> $metrics
     */
    private function add_metric(array &$metrics, string $name, float $revenue): void
    {
        $name = trim($name);
        if ($name === '') {
            $name = __('Unknown', 'calio-addon');
        }

        if (!isset($metrics[$name])) {
            $metrics[$name] = [
                'orders' => 0,
                'revenue' => 0.0,
            ];
        }

        ++$metrics[$name]['orders'];
        $metrics[$name]['revenue'] += $revenue;
    }

    /**
     * @param array<string, array{orders: int, revenue: float}> $metrics
     * @return array<int, array{name: string, orders: int, revenue: float}>
     */
    private function rank_metrics(array $metrics, int $limit): array
    {
        uasort(
            $metrics,
            static function (array $first, array $second): int {
                if ($first['revenue'] === $second['revenue']) {
                    return $second['orders'] <=> $first['orders'];
                }

                return $second['revenue'] <=> $first['revenue'];
            }
        );

        $rows = [];
        foreach ($metrics as $name => $metric) {
            $rows[] = [
                'name' => $name,
                'orders' => $metric['orders'],
                'revenue' => $metric['revenue'],
            ];
        }

        return $limit > 0 ? array_slice($rows, 0, $limit) : $rows;
    }

    private function country_name(string $country_code): string
    {
        if ($country_code === '' || !function_exists('WC')) {
            return __('Unknown country', 'calio-addon');
        }

        $countries = WC()->countries;
        if (!is_object($countries) || !method_exists($countries, 'get_countries')) {
            return strtoupper($country_code);
        }

        $labels = $countries->get_countries();
        return isset($labels[strtoupper($country_code)])
            ? sanitize_text_field((string) $labels[strtoupper($country_code)])
            : strtoupper($country_code);
    }

    private function traffic_source(\WC_Order $order): string
    {
        $source_type = sanitize_key((string) $order->get_meta('_wc_order_attribution_source_type'));
        $utm_source = strtolower(sanitize_text_field((string) $order->get_meta('_wc_order_attribution_utm_source')));
        $utm_medium = strtolower(sanitize_text_field((string) $order->get_meta('_wc_order_attribution_utm_medium')));

        if ($source_type === 'organic') {
            return __('Organic', 'calio-addon');
        }

        if ($source_type === 'typein') {
            return __('Direct', 'calio-addon');
        }

        if ($source_type === 'referral') {
            return __('Referral', 'calio-addon');
        }

        if ($source_type === 'admin') {
            return __('Web Admin', 'calio-addon');
        }

        if ($source_type === 'mobile_app') {
            return __('Mobile App', 'calio-addon');
        }

        if ($source_type === 'pos') {
            return __('Point of Sale', 'calio-addon');
        }

        if ($source_type === 'utm') {
            if (str_contains($utm_medium, 'email') || str_contains($utm_source, 'newsletter')) {
                return __('Email', 'calio-addon');
            }

            if (
                str_contains($utm_medium, 'social')
                || preg_match('/facebook|instagram|linkedin|pinterest|tiktok|youtube|twitter|x\\.com/', $utm_source)
            ) {
                return __('Social', 'calio-addon');
            }

            if (preg_match('/cpc|ppc|paid|display|cpm/', $utm_medium)) {
                return __('Paid', 'calio-addon');
            }

            if (str_contains($utm_medium, 'affiliate')) {
                return __('Affiliate', 'calio-addon');
            }

            return $utm_source !== ''
                ? sprintf(
                    /* translators: %s: UTM source name. */
                    __('Campaign: %s', 'calio-addon'),
                    ucfirst($utm_source)
                )
                : __('Campaign', 'calio-addon');
        }

        return __('Unknown', 'calio-addon');
    }

    /**
     * @param array<int, array{name: string, orders: int, revenue: float}> $rows
     */
    private function render_ranked_list(string $title, array $rows, string $type): void
    {
        echo '<section class="calio-marketing-hud__list">';
        echo '<h3>' . esc_html($title) . '</h3>';

        if ($rows === []) {
            echo '<p class="calio-marketing-hud__empty">' . esc_html__('No recent order data is available.', 'calio-addon') . '</p>';
            echo '</section>';
            return;
        }

        echo '<div class="calio-marketing-hud__rows" data-marketing-table="' . esc_attr($type) . '">';
        foreach ($rows as $index => $row) {
            echo '<div class="calio-marketing-hud__row"';
            echo ' data-name="' . esc_attr($row['name']) . '"';
            echo ' data-orders="' . esc_attr((string) $row['orders']) . '"';
            echo ' data-revenue="' . esc_attr(wc_format_decimal($row['revenue'], wc_get_price_decimals())) . '">';
            echo '<span class="calio-marketing-hud__rank">' . esc_html((string) ($index + 1)) . '</span>';
            echo '<div class="calio-marketing-hud__row-copy">';
            echo '<strong>' . esc_html($row['name']) . '</strong>';
            echo '<small>' . esc_html(
                sprintf(
                    /* translators: %d: number of orders. */
                    _n('%d order', '%d orders', $row['orders'], 'calio-addon'),
                    $row['orders']
                )
            ) . '</small>';
            echo '</div>';
            echo '<span class="calio-marketing-hud__revenue">' . esc_html(wp_strip_all_tags(wc_price($row['revenue']))) . '</span>';
            echo '</div>';
        }
        echo '</div>';
        echo '</section>';
    }

    private function can_view(): bool
    {
        return current_user_can('manage_options');
    }
}
