<?php
/**
 * Bizmart — Shared analytics helpers.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */

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

if (!function_exists('bizmart_analytics_reporting_statuses')) {
    function bizmart_analytics_reporting_statuses(): array {
        return ['completed', 'processing', 'on-hold'];
    }
}

if (!function_exists('bizmart_analytics_reporting_statuses_prefixed')) {
    function bizmart_analytics_reporting_statuses_prefixed(): array {
        return array_map(static function($status) {
            return 'wc-' . ltrim((string) $status, 'wc-');
        }, bizmart_analytics_reporting_statuses());
    }
}

if (!function_exists('bizmart_analytics_get_purchase_price')) {
    function bizmart_analytics_get_purchase_price($product_id) {
        $raw = get_post_meta($product_id, '_purchase_price', true);
        if ($raw === '' || $raw === null) {
            return null;
        }

        if (is_string($raw)) {
            $clean = preg_replace('/[^\d\.,-]/', '', $raw);
            if (substr_count($clean, ',') > 0 && substr_count($clean, '.') === 0) {
                $clean = str_replace(',', '.', $clean);
            } else {
                $clean = str_replace(',', '', $clean);
            }
            return is_numeric($clean) ? (float) $clean : null;
        }

        return is_numeric($raw) ? (float) $raw : null;
    }
}

if (!function_exists('bizmart_analytics_resolve_item_cost')) {
    function bizmart_analytics_resolve_item_cost($item, &$pp_cache) {
        $item_total = (float) $item->get_total();
        $item_id = $item->get_id();

        $signed_meta = wc_get_order_item_meta($item_id, '_bizmart_pos_signed_qty', true);
        if ($signed_meta !== '' && $signed_meta !== false) {
            $qty = (float) $signed_meta;
        } else {
            $qty = (int) $item->get_quantity();
            if ($item_total < 0 && $qty > 0) {
                $qty = -$qty;
            }
        }

        if ($qty < 0 || $item_total < 0) {
            return ['pp' => 0.0, 'qty' => $qty];
        }

        $is_pos_item = ($signed_meta !== '' && $signed_meta !== false);
        $snapshot = wc_get_order_item_meta($item_id, '_purchase_price', true);
        if ($snapshot !== '' && $snapshot !== false && is_numeric($snapshot)) {
            return ['pp' => (float) $snapshot, 'qty' => $qty];
        }

        if ($is_pos_item) {
            return ['pp' => 0.0, 'qty' => $qty];
        }

        $product = $item->get_product();
        if (!$product) {
            return ['pp' => null, 'qty' => $qty];
        }

        $product_id = $product->get_id();
        if (!array_key_exists($product_id, $pp_cache)) {
            $pp_cache[$product_id] = bizmart_analytics_get_purchase_price($product_id);
        }
        $pp = $pp_cache[$product_id];

        if ($pp === null && $product->is_type('variation') && method_exists($product, 'get_parent_id')) {
            $parent_id = (int) $product->get_parent_id();
            if ($parent_id > 0) {
                if (!array_key_exists($parent_id, $pp_cache)) {
                    $pp_cache[$parent_id] = bizmart_analytics_get_purchase_price($parent_id);
                }
                if ($pp_cache[$parent_id] !== null) {
                    $pp = $pp_cache[$parent_id];
                }
            }
        }

        return ['pp' => $pp, 'qty' => $qty];
    }
}

if (!function_exists('bizmart_analytics_get_order_line_metrics')) {
    function bizmart_analytics_get_order_line_metrics($order, array &$purchase_price_cache = []): array {
        $metrics = [
            'sales' => 0.0,
            'profit' => 0.0,
            'discounts' => 0.0,
        ];

        if (!$order || !($order instanceof WC_Order) || $order instanceof WC_Order_Refund) {
            return $metrics;
        }

        $metrics['discounts'] = (float) $order->get_total_discount();

        foreach ($order->get_items() as $item) {
            $item_total = (float) $item->get_total();
            $metrics['sales'] += $item_total;

            $resolved = bizmart_analytics_resolve_item_cost($item, $purchase_price_cache);
            $purchase_price = $resolved['pp'];
            $quantity = $resolved['qty'];
            $cost = ($purchase_price !== null) ? ((float) $purchase_price * (float) $quantity) : 0.0;

            $metrics['profit'] += ($item_total - $cost);
        }

        return $metrics;
    }
}

if (!function_exists('bizmart_analytics_get_orders_range')) {
    function bizmart_analytics_get_orders_range($after, $before, $statuses = null) {
        if (!function_exists('wc_get_orders')) {
            return [];
        }

        $normalized_statuses = [];
        foreach ((array) ($statuses ?: bizmart_analytics_reporting_statuses()) as $status) {
            $status = sanitize_key((string) $status);
            if ($status === '') {
                continue;
            }
            $normalized_statuses[] = strpos($status, 'wc-') === 0 ? substr($status, 3) : $status;
        }

        if (!$normalized_statuses) {
            $normalized_statuses = bizmart_analytics_reporting_statuses();
        }

        return wc_get_orders([
            'limit' => -1,
            'status' => array_values(array_unique($normalized_statuses)),
            'type' => 'shop_order',
            'date_created' => $after . ' 00:00:00...' . $before . ' 23:59:59',
        ]);
    }
}

if (!function_exists('bizmart_analytics_get_month_windows')) {
    function bizmart_analytics_get_month_windows(): array {
        $timezone = function_exists('wp_timezone') ? wp_timezone() : new DateTimeZone('UTC');
        $current_month_start = new DateTimeImmutable('first day of this month 00:00:00', $timezone);
        $last_month_start = $current_month_start->modify('-1 month');
        $last_month_end = $current_month_start->modify('-1 day');

        return [
            'today' => wp_date('Y-m-d'),
            'this_month_start' => $current_month_start->format('Y-m-d'),
            'last_month_start' => $last_month_start->format('Y-m-d'),
            'last_month_end' => $last_month_end->format('Y-m-d'),
        ];
    }
}