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

function elementsell_render_admin_statistics() {
    $current_year  = (int) current_time( 'Y' );
    $current_month = (int) current_time( 'm' );

    $months = [
        'Leden', 'Únor', 'Březen', 'Duben', 'Květen', 'Červen',
        'Červenec', 'Srpen', 'Září', 'Říjen', 'Listopad', 'Prosinec',
    ];

    $current_month_name      = $months[ $current_month - 1 ];
    $current_month_total     = elementsell_sales_stats_get_month_revenue( $current_year, $current_month );
    $current_year_totals     = elementsell_sales_stats_get_year_month_totals( $current_year );
    $historical_by_month     = elementsell_sales_stats_get_historical_by_month( $current_year );
    $last_12_months_total    = elementsell_sales_stats_get_last_12_months_revenue();

    $max_historical_totals = array_map(
        static function ( $month_data ) {
            return ! empty( $month_data ) ? max( $month_data ) : 0;
        },
        $historical_by_month
    );

    $chart_month_details = [];

    for ( $i = 0; $i < 12; $i++ ) {
        $details = [];

        if ( $current_year_totals[ $i ] > 0 ) {
            $details[] = [
                'year'  => $current_year,
                'total' => $current_year_totals[ $i ],
            ];
        }

        if ( ! empty( $historical_by_month[ $i ] ) ) {
            $years = $historical_by_month[ $i ];
            krsort( $years, SORT_NUMERIC );

            foreach ( $years as $year => $total ) {
                if ( $total > 0 ) {
                    $details[] = [
                        'year'  => (int) $year,
                        'total' => (int) $total,
                    ];
                }
            }
        }

        $chart_month_details[] = $details;
    }

    $datasets = [
        [
            'label'           => 'Uhrazeno ' . $current_year,
            'data'            => $current_year_totals,
            'backgroundColor' => 'rgba(34, 113, 177, 0.88)',
            'borderColor'     => 'rgba(34, 113, 177, 1)',
            'borderWidth'     => 0,
            'borderRadius'    => 6,
        ],
        [
            'label'           => 'Nejlepší rok v minulosti',
            'data'            => $max_historical_totals,
            'backgroundColor' => 'rgba(34, 113, 177, 0.22)',
            'borderColor'     => 'rgba(34, 113, 177, 0.35)',
            'borderWidth'     => 0,
            'borderRadius'    => 6,
        ],
    ];

    echo '<div class="elementsell-admin-card elementsell-admin-stats">';
    echo '<div class="elementsell-admin-stats__header">';
    echo '<h2>Příjem za ' . esc_html( $current_month_name ) . '</h2>';
    echo '<div class="elementsell-admin-stats__highlight">' . esc_html( number_format( $current_month_total, 0, ',', ' ' ) ) . ' Kč</div>';
    echo '</div>';

    echo '<div class="elementsell-admin-stats__layout">';
    echo '<div class="elementsell-admin-stats__chart"><canvas id="elementsellRevenueChart" width="760" height="320"></canvas></div>';

    echo '<div class="elementsell-admin-stats__metrics">';
    echo '<div class="elementsell-admin-metric"><strong>Příjem v roce ' . esc_html( $current_year ) . '</strong><span>' . esc_html( number_format( array_sum( $current_year_totals ), 0, ',', ' ' ) ) . ' Kč</span></div>';
    echo '<div class="elementsell-admin-metric"><strong>Příjem za posledních 12 měsíců</strong><span>' . esc_html( number_format( $last_12_months_total, 0, ',', ' ' ) ) . ' Kč</span></div>';
    echo '<p class="elementsell-stats-detail-link"><a href="' . esc_url( elementsell_get_sales_statistics_admin_url() ) . '">Statistiky</a>';
    if ( function_exists( 'elementsell_get_mailing_list_admin_url' ) ) {
        echo ' · <a href="' . esc_url( elementsell_get_mailing_list_admin_url() ) . '">Mailing list</a>';
    }
    if (
        function_exists( 'elementsell_is_landing_enabled' )
        && elementsell_is_landing_enabled()
        && function_exists( 'elementsell_get_landing_leads_admin_url' )
    ) {
        $leads_count = function_exists( 'elementsell_get_landing_leads_count' ) ? elementsell_get_landing_leads_count() : 0;
        echo ' · <a href="' . esc_url( elementsell_get_landing_leads_admin_url() ) . '">Poptávky';
        if ( $leads_count > 0 ) {
            echo ' (' . esc_html( number_format_i18n( $leads_count ) ) . ')';
        }
        echo '</a>';
    }
    echo '</p>';
    echo '<div class="elementsell-stats-search">';
    elementsell_render_record_search_field(
        [
            'class' => 'elementsell-record-search--metrics',
        ]
    );
    echo '</div>';
    echo '</div>';

    echo '</div>';
    echo '</div>';

    echo '<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>';
    echo '<script>
        document.addEventListener("DOMContentLoaded", function() {
            const ctx = document.getElementById("elementsellRevenueChart");
            if (!ctx) return;

            const monthLabels = ' . wp_json_encode( $months ) . ';
            const chartMonthDetails = ' . wp_json_encode( $chart_month_details ) . ';

            function formatRevenue(value) {
                return new Intl.NumberFormat("cs-CZ", {
                    maximumFractionDigits: 0
                }).format(value) + " Kč";
            }

            new Chart(ctx, {
                type: "bar",
                data: {
                    labels: monthLabels,
                    datasets: ' . wp_json_encode( $datasets ) . '
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: "index",
                        intersect: false
                    },
                    plugins: {
                        legend: {
                            labels: {
                                boxWidth: 12,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            displayColors: false,
                            callbacks: {
                                title: function(items) {
                                    return items.length ? monthLabels[items[0].dataIndex] : "";
                                },
                                label: function() {
                                    return "";
                                },
                                afterBody: function(items) {
                                    if (!items.length) {
                                        return [];
                                    }

                                    const details = chartMonthDetails[items[0].dataIndex] || [];

                                    if (!details.length) {
                                        return ["Bez příjmu"];
                                    }

                                    return details.map(function(item) {
                                        return item.year + ": " + formatRevenue(item.total);
                                    });
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: "rgba(0,0,0,0.06)"
                            }
                        }
                    }
                }
            });
        });
    </script>';
}
