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

/**
 * Anbaarak | Best Inventory management plugin for WooCommerce.
 * All rights reserved for WP LEGEND team (wplegend.ir)
 */


function anbarak_calculate_period_stats($date_start, $date_end)
{
    $orders = anbarak_get_sales($date_start, $date_end);
    $total_orders = count($orders);
    $total_sell_price = anbarak_get_total_sale_price($date_start, $date_end);
    $gross_profit = anbarak_get_orders_gross_profit($date_start, $date_end);
    $expenses = anbarak_get_total_expenses_price($date_start, $date_end);
    $purchase_tag = anbarak_get_purchase_tag_id();
    $product_purchase = anbarak_get_total_expenses_price($date_start, $date_end, $purchase_tag);
    $net_profit = $gross_profit - ($expenses - $product_purchase);
    $avg_items = anbarak_get_order_items_avg($date_start, $date_end);

    $online_sales = anbarak_get_total_sale_price($date_start, $date_end, 'online');
    $offline_sales = anbarak_get_total_sale_price($date_start, $date_end, 'in-store');
    $online_count = count(anbarak_get_sales($date_start, $date_end, 'online'));
    $offline_count = count(anbarak_get_sales($date_start, $date_end, 'in-store'));

    $period_days = max(1, round(($date_end - $date_start) / 86400));
    $avg_daily_orders = round($total_orders / $period_days, 1);
    $margin = $total_sell_price ? round(($gross_profit / $total_sell_price) * 100, 1) : 0;

    return compact(
        'total_orders', 'total_sell_price', 'gross_profit',
        'expenses', 'net_profit', 'avg_items', 'online_sales', 'offline_sales',
        'online_count', 'offline_count', 'period_days', 'avg_daily_orders', 'margin'
    );
}

function anbarak_get_expenses_distribution(int $date_start, int $date_end)
{
    $tags = anbarak_get_expenses_tags();
    $distribution = [];
    $colors = [];

    foreach ($tags as $tag) {
        $tag_id = isset($tag->id) ? (int) $tag->id : 0;

        if (!$tag_id) {
            continue;
        }

        $expenses = anbarak_get_month_expenses($date_start, $date_end, $tag_id);
        $total = array_sum(array_column($expenses, 1));

        if ($total <= 0) {
            continue;
        }

        $distribution[] = [
            'name'  => isset($tag->name) ? $tag->name : esc_html__('No tag', 'anbarak'),
            'y'     => (int) $total,
            'color' => isset($tag->color) ? $tag->color : '#777777',
        ];
    }

    usort($distribution, function ($a, $b) {
        return $b['y'] <=> $a['y'];
    });

    $colors = array_column($distribution, 'color');

    return [
        'expenses' => $distribution,
        'colors'   => $colors,
    ];
}

function anbarak_render_expenses_distribution_stats(int $date_start, int $date_end)
{
    $distribution = anbarak_get_expenses_distribution($date_start, $date_end);
    $expenses = $distribution['expenses'];
    $total = array_sum(array_column($expenses, 'y'));
    $categories_count = count($expenses);
    $period_days = max(1, (int) ceil(($date_end - $date_start) / DAY_IN_SECONDS));
    $daily_average = $total / $period_days;
    $top_expense = $expenses[0] ?? null;
    $top_percent = $top_expense && $total ? round(((int) $top_expense['y'] / $total) * 100, 1) : 0;
    ?>
    <div class="expense-report-summary grid grid-cols-1 md:grid-cols-2 gap-3 mb-4">
        <div class="box !p-4">
            <div class="text-xs text-gray-500 dark:text-gray-400 mb-1"><?php esc_html_e('Total expenses', 'anbarak'); ?></div>
            <div class="text-lg font-bold ltr"><?php echo wp_kses_post(wc_price($total)); ?></div>
        </div>
        <div class="box !p-4">
            <div class="text-xs text-gray-500 dark:text-gray-400 mb-1"><?php esc_html_e('Daily average', 'anbarak'); ?></div>
            <div class="text-lg font-bold ltr"><?php echo wp_kses_post(wc_price($daily_average)); ?></div>
        </div>
        <div class="box !p-4">
            <div class="text-xs text-gray-500 dark:text-gray-400 mb-1"><?php esc_html_e('Active categories', 'anbarak'); ?></div>
            <div class="text-lg font-bold"><?php echo esc_html(number_format_i18n($categories_count)); ?></div>
        </div>
        <div class="box !p-4">
            <div class="text-xs text-gray-500 dark:text-gray-400 mb-1"><?php esc_html_e('Top category', 'anbarak'); ?></div>
            <?php if ($top_expense) : ?>
                <div class="flex items-center gap-2 min-w-0">
                    <span class="w-2.5 h-2.5 rounded-full shrink-0" style="background-color: <?php echo esc_attr($top_expense['color']); ?>"></span>
                    <span class="font-bold truncate"><?php echo esc_html($top_expense['name']); ?></span>
                    <span class="badge ms-auto ltr"><?php echo esc_html($top_percent); ?>%</span>
                </div>
            <?php else : ?>
                <div class="text-gray-400"><?php esc_html_e('Nothing found', 'anbarak'); ?></div>
            <?php endif; ?>
        </div>
    </div>

    <div class="box !p-0 overflow-hidden mb-4">
        <div class="flex items-center gap-2 px-5 py-4 border-b border-gray-100 dark:border-[#333]">
            <i class="icon icon-bar-chart text-lg text-gray-500 dark:text-gray-400"></i>
            <h2 class="font-bold text-base m-0"><?php esc_html_e('Expense Categories', 'anbarak'); ?></h2>
        </div>
        <?php if ($expenses) : ?>
            <div class="divide-y divide-gray-100 dark:divide-[#333]">
                <?php foreach (array_slice($expenses, 0, 8) as $expense) : ?>
                    <?php $percent = $total ? round(((int) $expense['y'] / $total) * 100, 1) : 0; ?>
                    <div class="p-4 grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_140px_80px] gap-2 xl:items-center">
                        <div class="min-w-0 flex items-center gap-2">
                            <span class="w-2.5 h-2.5 rounded-full shrink-0" style="background-color: <?php echo esc_attr($expense['color']); ?>"></span>
                            <span class="font-semibold truncate"><?php echo esc_html($expense['name']); ?></span>
                        </div>
                        <div class="h-2 bg-gray-100 dark:bg-[#252525] rounded-full overflow-hidden">
                            <div class="h-full rounded-full" style="width: <?php echo esc_attr($percent); ?>%; background-color: <?php echo esc_attr($expense['color']); ?>"></div>
                        </div>
                        <div class="flex xl:flex-col gap-2 xl:gap-0 xl:text-end text-sm">
                            <span class="font-bold ltr"><?php echo wp_kses_post(wc_price($expense['y'])); ?></span>
                            <span class="text-gray-400 ltr"><?php echo esc_html($percent); ?>%</span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else : ?>
            <div class="p-6 text-center text-gray-400"><?php esc_html_e('Nothing found', 'anbarak'); ?></div>
        <?php endif; ?>
    </div>

    <div id="expenses-share" hidden>
        <?php echo esc_html(wp_json_encode($distribution['expenses'])); ?>
    </div>
    <div id="tags-color" hidden>
        <?php echo esc_html(wp_json_encode($distribution['colors'])); ?>
    </div>
    <?php
}

function anbarak_render_filtered_stats($date_start, $date_end)
{
    $stats = anbarak_calculate_period_stats($date_start, $date_end);

    $prev_duration = $date_end - $date_start;
    $prev_start = max(0, $date_start - $prev_duration);
    $prev_end = max(0, $date_start - 1);
    $prev_stats = anbarak_calculate_period_stats($prev_start, $prev_end);

    $diff_orders = $prev_stats['total_orders'] ? round((($stats['total_orders'] - $prev_stats['total_orders']) / $prev_stats['total_orders']) * 100, 1) : 0;
    $diff_sales = $prev_stats['total_sell_price'] ? round((($stats['total_sell_price'] - $prev_stats['total_sell_price']) / $prev_stats['total_sell_price']) * 100, 1) : 0;
    $diff_profit = $prev_stats['gross_profit'] ? round((($stats['gross_profit'] - $prev_stats['gross_profit']) / $prev_stats['gross_profit']) * 100, 1) : 0;
    $diff_net = $prev_stats['net_profit'] ? round((($stats['net_profit'] - $prev_stats['net_profit']) / $prev_stats['net_profit']) * 100, 1) : 0;

    ?>
    <div class="box !p-0 divide-y lg:divide-y-0 lg:divide-x divide-gray-100 dark:divide-neutral-800 rtl:divide-x-reverse grid grid-cols-2 lg:grid-cols-6 rounded-2xl overflow-hidden">
        <div class="p-3 text-center stat-card">
            <div class="text-lg font-bold"><?php echo esc_html(number_format($stats['total_orders'])); ?></div>
            <div class="text-gray-500 mt-0.5"><?php esc_html_e('Orders', 'anbarak'); ?></div>
            <div class="flex items-center justify-center gap-1.5 mt-1">
                <span class="text-[10px] text-gray-400 ltr"><?php echo esc_html($stats['avg_daily_orders']); ?>/d</span>
                <?php if ($diff_orders) : ?>
                    <span class="text-[10px] px-1 py-0.5 rounded-full leading-none <?php echo $diff_orders > 0 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'; ?> ltr"><?php echo $diff_orders > 0 ? '↑' : '↓'; ?><?php echo esc_html(abs($diff_orders)); ?>%</span>
                <?php endif; ?>
            </div>
        </div>
        <div class="p-3 text-center stat-card">
            <div class="text-lg font-bold ltr"><?php echo wp_kses_post(wc_price($stats['total_sell_price'])); ?></div>
            <div class="text-gray-500 mt-0.5"><?php esc_html_e('Sales', 'anbarak'); ?></div>
            <div class="flex items-center justify-center gap-1.5 mt-1">
                <span class="text-[10px] text-gray-400 ltr"><?php echo wp_kses_post(sprintf(/* translators: %s: formatted price */ __('Online %s', 'anbarak'), wc_price($stats['online_sales']))); ?></span>
                <span class="text-[10px] text-gray-300">·</span>
                <span class="text-[10px] text-gray-400 ltr"><?php echo wp_kses_post(sprintf(/* translators: %s: formatted price */ __('In-store %s', 'anbarak'), wc_price($stats['offline_sales']))); ?></span>
                <?php if ($diff_sales) : ?>
                    <span class="text-[10px] px-1 py-0.5 rounded-full leading-none <?php echo $diff_sales > 0 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'; ?> ltr"><?php echo $diff_sales > 0 ? '↑' : '↓'; ?><?php echo esc_html(abs($diff_sales)); ?>%</span>
                <?php endif; ?>
            </div>
        </div>
        <div class="p-3 text-center stat-card">
            <div class="text-lg font-bold ltr"><?php echo wp_kses_post(wc_price($stats['gross_profit'])); ?></div>
            <div class="text-gray-500 mt-0.5"><?php esc_html_e('Gross Profit', 'anbarak'); ?></div>
            <div class="flex items-center justify-center gap-1.5 mt-1">
                <span class="text-[10px] px-1 py-0.5 rounded-full leading-none bg-primary/10 text-primary ltr"><?php echo esc_html($stats['margin']); ?>%</span>
                <?php if ($diff_profit) : ?>
                    <span class="text-[10px] px-1 py-0.5 rounded-full leading-none <?php echo $diff_profit > 0 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'; ?> ltr"><?php echo $diff_profit > 0 ? '↑' : '↓'; ?><?php echo esc_html(abs($diff_profit)); ?>%</span>
                <?php endif; ?>
            </div>
        </div>
        <div class="p-3 text-center stat-card">
            <div class="text-lg font-bold ltr"><?php echo wp_kses_post(wc_price($stats['expenses'])); ?></div>
            <div class="text-gray-500 mt-0.5"><?php esc_html_e('Expenses', 'anbarak'); ?></div>
        </div>
        <div class="p-3 text-center stat-card">
            <div class="text-lg font-bold ltr <?php echo $stats['net_profit'] < 0 ? 'text-red-500' : 'text-green-600'; ?>"><?php echo wp_kses_post(wc_price($stats['net_profit'])); ?></div>
            <div class="text-gray-500 mt-0.5"><?php esc_html_e('Net Profit', 'anbarak'); ?></div>
            <?php if ($diff_net) : ?>
                <div class="flex items-center justify-center gap-1.5 mt-1">
                    <span class="text-[10px] px-1 py-0.5 rounded-full leading-none <?php echo $diff_net > 0 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'; ?> ltr"><?php echo $diff_net > 0 ? '↑' : '↓'; ?><?php echo esc_html(abs($diff_net)); ?>%</span>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php
    anbarak_render_stats_chart_data_scripts($date_start, $date_end);
}

function anbarak_render_stats_chart_data_scripts($date_start, $date_end)
{
    $six_month_start = $date_start - (180 * 86400);
    ?>
    <div id="ajax-month-sales-all" hidden>
        <?php echo esc_html(wp_json_encode(@anbarak_get_month_sales_prices($date_start, $date_end))); ?>
    </div>
    <div id="ajax-month-sales-online" hidden>
        <?php echo esc_html(wp_json_encode(@anbarak_get_month_sales_prices($date_start, $date_end, 'online'))); ?>
    </div>
    <div id="ajax-month-sales-in-store" hidden>
        <?php echo esc_html(wp_json_encode(@anbarak_get_month_sales_prices($date_start, $date_end, 'in-store'))); ?>
    </div>
    <div id="ajax-month-expense" hidden>
        <?php echo esc_html(wp_json_encode(anbarak_get_month_expenses($date_start, $date_end))); ?>
    </div>
    <div id="ajax-month-profit" hidden>
        <?php echo esc_html(wp_json_encode(@anbarak_get_month_sales_profit($date_start, $date_end))); ?>
    </div>
    <div id="ajax-month-share" hidden>
        <?php
        $sales = array(
            'online' => count(anbarak_get_sales($date_start, $date_end, 'online')),
            'offline' => count(anbarak_get_sales($date_start, $date_end, 'in-store')),
        );
        echo esc_html(wp_json_encode($sales));
        ?>
    </div>
    <div id="ajax-month-name" hidden>
        <?php echo esc_html(wp_json_encode(anbarak_date_format('Y', $date_start) . ' ' . anbarak_date_format('F', $date_start))); ?>
    </div>
    <div id="ajax-last-six-month-sales-all" hidden>
        <?php echo esc_html(wp_json_encode(@anbarak_get_month_sales_prices($six_month_start, $date_end))); ?>
    </div>
    <div id="ajax-last-six-month-profit" hidden>
        <?php echo esc_html(wp_json_encode(@anbarak_get_month_sales_profit($six_month_start, $date_end))); ?>
    </div>
<?php
}
