<?php
/**
 * Bizmart — Analytics Dashboard.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;



/**
 * Helper: normalize purchase price from meta
 * Checks `_purchase_price` as required.
 */
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;

    // Normalize strings with commas or spaces
    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);
        }
        if (is_numeric($clean)) return (float)$clean;
        return null;
    }
    if (is_numeric($raw)) return (float)$raw;
    return null;
    }
}

/**
 * Build product purchase price map and stock value
 * Includes variable products: will use variation price if parent not set.
 */
$products_without_price = [];
$missing_purchase_price_count = 0;
$stock_value = 0.0;

// Count active products (publish, private, draft) - excluding trash
$total_products = 0;
if (function_exists('wp_count_posts')) {
    $counts = wp_count_posts('product');
    $total_products = (int) (($counts->publish ?? 0) + ($counts->private ?? 0) + ($counts->draft ?? 0));
}

// Cache heavy dashboard stats to keep admin fast on large stores.
$dash_cache_ttl = 10 * MINUTE_IN_SECONDS;

// WooCommerce may be disabled on some sites; keep dashboard functional.
$bizmart_wc_active = function_exists('wc_get_orders') && function_exists('wc_price') && function_exists('get_woocommerce_currency');

if (!function_exists('bizmart_dash_money')) {
    function bizmart_dash_money($amount) {
        if (function_exists('wc_price')) {
            return wc_price($amount);
        }
        $currency = '';
        if (function_exists('bizmart_get_currency_symbol')) {
            $currency = bizmart_get_currency_symbol();
        } elseif (function_exists('bizmart_get_option')) {
            $currency = (string) bizmart_get_option('biz_default_currency', '');
        }
        return number_format((float)$amount, 2) . ($currency !== '' ? (' ' . $currency) : '');
    }
}

// Inventory totals (RULE A: manage_stock=yes only). Cached briefly and invalidated on stock/price changes.
try {
    $inv_totals = function_exists('bizmart_metrics_get_inventory_totals')
        ? bizmart_metrics_get_inventory_totals(true)
        : ['stock_sales_value' => 0, 'stock_purchase_value' => 0, 'total_stock_qty' => 0];
} catch (\Throwable $e) {
    $inv_totals = ['stock_sales_value' => 0, 'stock_purchase_value' => 0, 'total_stock_qty' => 0];
    error_log('[Bizmart Dashboard] Inventory totals error: ' . $e->getMessage());
}

$stock_value = (float) ($inv_totals['stock_sales_value'] ?? 0);
$stock_purchase_value = (float) ($inv_totals['stock_purchase_value'] ?? 0);
// Missing purchase price: get total count + a limited list for the UI.
try {
$missing_cached = get_transient('bizmart_dash_missing_purchase_prices_v2');
if (is_array($missing_cached) && isset($missing_cached['count'], $missing_cached['items']) && is_array($missing_cached['items'])) {
    $missing_purchase_price_count = (int) $missing_cached['count'];
    $products_without_price = $missing_cached['items'];
} else {
    $missing_query = new WP_Query([
        'post_type'      => 'product',
        'post_status'    => ['publish', 'draft', 'private'],
        'posts_per_page' => 50,
        'fields'         => 'ids',
        'no_found_rows'  => false,
        'meta_query'     => [
            'relation' => 'OR',
            [
                'key'     => '_purchase_price',
                'compare' => 'NOT EXISTS',
            ],
            [
                'key'     => '_purchase_price',
                'value'   => '',
                'compare' => '=',
            ],
            [
                'key'     => '_purchase_price',
                'value'   => 0,
                'type'    => 'NUMERIC',
                'compare' => '<=',
            ],
        ],
    ]);

    $missing_purchase_price_count = (int) $missing_query->found_posts;
    $products_without_price = [];
    if (!empty($missing_query->posts)) {
        foreach ($missing_query->posts as $pid) {
            $product = wc_get_product($pid);
            if (!$product) continue;

            // Smart condition: If this is a variable product and ALL its variations
            // have a purchase price, consider the parent as "covered" and skip it.
            if ($product->is_type('variable')) {
                $variation_ids = $product->get_children();
                if (!empty($variation_ids)) {
                    $all_variations_have_price = true;
                    foreach ($variation_ids as $vid) {
                        $vp = (float) get_post_meta($vid, '_purchase_price', true);
                        if ($vp <= 0) {
                            $all_variations_have_price = false;
                            break;
                        }
                    }
                    if ($all_variations_have_price) {
                        $missing_purchase_price_count--;
                        continue; // Skip — all variations are priced
                    }
                }
            }
            
            $products_without_price[] = [
                'id'   => (int) $pid,
                'name' => $product->get_name(),
                'sku'  => $product->get_sku(),
                'link' => get_edit_post_link($pid),
                'type' => $product->get_type(),
                'variation_ids' => $product->is_type('variable') ? $product->get_children() : [],
            ];
        }
    }
    // Ensure count doesn't go negative after skipping covered variables
    $missing_purchase_price_count = max(0, $missing_purchase_price_count);

    set_transient('bizmart_dash_missing_purchase_prices_v2', [
        'count' => $missing_purchase_price_count,
        'items' => $products_without_price,
    ], $dash_cache_ttl);
}
} catch (\Throwable $e) {
    error_log('[Bizmart Dashboard] Missing prices query error: ' . $e->getMessage());
}

// Purchase price cache for order processing (avoid full product preload)
$purchase_price_cache = [];

/**
 * Date range handling for chart toggles
 */
$range = isset($_GET['range']) ? sanitize_text_field(wp_unslash($_GET['range'])) : '7';
$start_date_param = isset($_GET['start_date']) ? sanitize_text_field(wp_unslash($_GET['start_date'])) : '';
$end_date_param = isset($_GET['end_date']) ? sanitize_text_field(wp_unslash($_GET['end_date'])) : '';

if (!in_array($range, ['7', '30', 'all'], true)) $range = '7';

$end_date = wp_date('Y-m-d');
$first_order_date = wp_date('Y-m-d');
$first_data_date = $first_order_date;

if ($bizmart_wc_active) {
    $first = wc_get_orders([
        'limit'  => 1,
        'orderby'=> 'date_created',
        'order'  => 'ASC',
        'type'   => 'shop_order',
        'status' => ['completed', 'processing', 'on-hold'],
    ]);
    if (!empty($first) && isset($first[0])) {
        $d = $first[0]->get_date_created();
        if ($d) {
            $first_order_date = $d->date('Y-m-d');
        }
    }
}

// For "Since the beginning", start from the first available data (orders OR expenses)
$first_data_date = $first_order_date;
global $wpdb;
$expenses_table_min = $wpdb->prefix . 'bizmart_expenses';
if (bizmart_table_exists('bizmart_expenses')) {
    // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
    $min_exp = $wpdb->get_var(
        $wpdb->prepare("SELECT MIN(expense_date) FROM {$expenses_table_min} WHERE expense_date > %s", '1970-01-01')
    );
    if (!empty($min_exp) && preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)$min_exp)) {
        $min_exp_ts = strtotime((string)$min_exp);
        // Reject zero/invalid dates (0000-00-00, dates before 2000, etc.)
        if ($min_exp_ts !== false && $min_exp_ts > 946684800 && $min_exp_ts < strtotime($first_data_date)) {
            $first_data_date = (string)$min_exp;
        }
    }
}

if (!empty($start_date_param) && !empty($end_date_param)) {
    $start_date = $start_date_param;
    $end_date = $end_date_param;
    // Validate dates
    if (strtotime($start_date) > strtotime($end_date)) {
        $temp = $start_date;
        $start_date = $end_date;
        $end_date = $temp;
    }
} else {
    $start_date = ($range === '7') ? wp_date('Y-m-d', strtotime('-6 days'))
    : (($range === '30') ? wp_date('Y-m-d', strtotime('-29 days')) : $first_data_date);
}

/**
 * Safe order fetcher: excludes refunds.
 *
 * Uses WC's documented `date_after` / `date_before` top-level args which are
 * internally converted to the `date_created` range syntax by wc_get_orders().
 * This approach works identically on HPOS and legacy CPT data-stores.
 */
if (!function_exists('bizmart_analytics_get_orders_range')) {
    function bizmart_analytics_get_orders_range($after, $before) {
        if (!function_exists('wc_get_orders')) {
            return [];
        }

        $args = [
            'limit'        => -1, // Must aggregate ALL orders in the date range for accurate analytics
            'status'       => ['completed', 'processing', 'on-hold'],
            'type'         => 'shop_order',
            'date_after'   => $after,
            'date_before'  => $before . ' 23:59:59',
        ];

        return wc_get_orders($args);
    }
}

if (!function_exists('bizmart_analytics_get_expenses_range')) {
    function bizmart_analytics_get_expenses_range($start_date, $end_date) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'bizmart_expenses';
        if (!bizmart_table_exists('bizmart_expenses')) {
            return [];
        }
        return $wpdb->get_results($wpdb->prepare(
            "SELECT expense_date, amount FROM $table_name WHERE expense_date >= %s AND expense_date <= %s",
            $start_date, $end_date
        ));
    }
}

$orders_range  = [];
$expenses_range = [];
$dashboard_data_error = false;

try {
    $orders_range  = bizmart_analytics_get_orders_range($start_date, $end_date);
    $expenses_range = bizmart_analytics_get_expenses_range($start_date, $end_date);
} catch (\Throwable $e) {
    $dashboard_data_error = true;
    error_log('[Bizmart Dashboard] Data fetch error: ' . $e->getMessage());
}

/**
 * Buckets for chart
 */
$chart_labels = [];
$chart_sales  = [];
$chart_profit = [];
$agg_by_date  = [];

// Safety: validate dates before creating DatePeriod
$start_ts = strtotime($start_date);
$end_ts   = strtotime($end_date);
if ($start_ts === false || $start_ts < 946684800) { // before 2000-01-01 = invalid
    $start_date = wp_date('Y-m-d', strtotime('-6 days'));
    $start_ts   = strtotime($start_date);
}
if ($end_ts === false || $end_ts < $start_ts) {
    $end_date = wp_date('Y-m-d');
    $end_ts   = strtotime($end_date);
}
// Cap chart to ~3 years to prevent memory exhaustion
$range_days_chart = (int) floor(($end_ts - $start_ts) / 86400) + 1;
if ($range_days_chart > 1100) {
    $start_date = wp_date('Y-m-d', strtotime($end_date . ' -1099 days'));
}

$period = new DatePeriod(new DateTime($start_date), new DateInterval('P1D'), (new DateTime($end_date))->modify('+1 day'));
foreach ($period as $dt) {
    $k = $dt->format('Y-m-d');
    $agg_by_date[$k] = ['sales' => 0.0, 'profit' => 0.0, 'expenses' => 0.0, 'net_profit' => 0.0];
    $chart_labels[]   = date_i18n('d M', strtotime($k));
}

/**
 * Metrics windows (today/week/month/year/all)
 */
$metrics = [
    'today' => ['sales'=>0.0,'profit'=>0.0,'orders'=>0,'discounts'=>0.0,'expenses'=>0.0,'net_profit'=>0.0],
    'week'  => ['sales'=>0.0,'profit'=>0.0,'orders'=>0,'discounts'=>0.0,'expenses'=>0.0,'net_profit'=>0.0],
    'month' => ['sales'=>0.0,'profit'=>0.0,'orders'=>0,'discounts'=>0.0,'expenses'=>0.0,'net_profit'=>0.0],
    'year'  => ['sales'=>0.0,'profit'=>0.0,'orders'=>0,'discounts'=>0.0,'expenses'=>0.0,'net_profit'=>0.0],
    'all'   => ['sales'=>0.0,'profit'=>0.0,'orders'=>0,'discounts'=>0.0,'expenses'=>0.0,'net_profit'=>0.0]
];

$products_agg = [];
$orders_list  = [];

$today_str       = wp_date('Y-m-d');
$week_start_str  = wp_date('Y-m-d', strtotime('-6 days'));
$month_start_str = wp_date('Y-m-01');
$year_start_str  = wp_date('Y-01-01');

/**
 * Process orders — wrapped in try/catch so a single bad order can't blank the dashboard.
 */
try {
foreach ($orders_range as $order) {
    // Safety: skip refunds
    if ($order instanceof WC_Order_Refund) continue;

    $order_id   = $order->get_id();
    $date       = $order->get_date_created() ? $order->get_date_created()->date('Y-m-d') : $today_str;
    $total      = (float)$order->get_total();

    // Discounts
    $discount = (float)$order->get_total_discount();
    foreach ($order->get_items() as $item) {
        $discount += max(0.0, ((float)$item->get_subtotal() - (float)$item->get_total()));
    }

    // Profit: sum of line totals minus (qty * purchase price)
    $profit = 0.0;
    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        if (!$product) continue;

        $pid        = $product->get_id();
        $qty        = (int)$item->get_quantity();
        $item_total = (float)$item->get_total();

        // Resolve purchase price per product/variation
        if (!array_key_exists($pid, $purchase_price_cache)) {
            $purchase_price_cache[$pid] = bizmart_analytics_get_purchase_price($pid);
        }
        $pp = $purchase_price_cache[$pid];

        // Variation: fallback to parent purchase price if variation doesn't have one.
        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, $purchase_price_cache)) {
                    $purchase_price_cache[$parent_id] = bizmart_analytics_get_purchase_price($parent_id);
                }
                if ($purchase_price_cache[$parent_id] !== null) {
                    $pp = $purchase_price_cache[$parent_id];
                }
            }
        }

        $cost        = ($pp !== null) ? ($pp * $qty) : 0.0;
        $line_profit = $item_total - $cost;
        $profit     += $line_profit;

        if (!isset($products_agg[$pid])) {
            $products_agg[$pid] = [
                'id'             => $pid,
                'name'           => $product->get_name(),
                'qty'            => 0,
                'sales'          => 0.0,
                'profit'         => 0.0,
                'link'           => get_edit_post_link($pid),
                'purchase_price' => $pp
            ];
        }
        $products_agg[$pid]['qty']    += $qty;
        $products_agg[$pid]['sales']  += $item_total;
        $products_agg[$pid]['profit'] += $line_profit;
    }

    // Aggregate by date for chart
    if (isset($agg_by_date[$date])) {
        $agg_by_date[$date]['sales']  += $total;
        $agg_by_date[$date]['profit'] += $profit;
    }

    // Orders list
    $order_number = method_exists($order, 'get_order_number') ? $order->get_order_number() : (string)$order_id;
    $orders_list[] = [
        'id'     => $order_id,
        'number' => $order_number,
        'total'  => $total,
        'profit' => $profit,
        'link'   => get_edit_post_link($order_id),
        'date'   => $date
    ];

    // Global metrics
    $metrics['all']['sales']     += $total;
    $metrics['all']['profit']    += $profit;
    $metrics['all']['orders']    += 1;
    $metrics['all']['discounts'] += $discount;

    // Windowed metrics
    foreach ([
        'today' => $today_str,
        'week'  => $week_start_str,
        'month' => $month_start_str,
        'year'  => $year_start_str
    ] as $key => $start) {
        if ($date >= $start) {
            $metrics[$key]['sales']     += $total;
            $metrics[$key]['profit']    += $profit;
            $metrics[$key]['orders']    += 1;
            $metrics[$key]['discounts'] += $discount;
        }
    }
}

// Process expenses
foreach ($expenses_range as $expense) {
    $date = $expense->expense_date;
    $amount = (float)$expense->amount;
    
    if (isset($agg_by_date[$date])) {
        $agg_by_date[$date]['expenses'] += $amount;
    }
    
    $metrics['all']['expenses'] += $amount;
    
    foreach (['today' => $today_str, 'week' => $week_start_str, 'month' => $month_start_str, 'year' => $year_start_str] as $key => $start) {
        if ($date >= $start) {
            $metrics[$key]['expenses'] += $amount;
        }
    }
}
} catch (\Throwable $e) {
    $dashboard_data_error = true;
    error_log('[Bizmart Dashboard] Order/expense processing error: ' . $e->getMessage());
}

// Calculate net profit (profit - expenses) for each period
foreach ($agg_by_date as $k => &$v) {
    $v['net_profit'] = $v['profit'] - $v['expenses'];
}
unset($v);

foreach (['today', 'week', 'month', 'year', 'all'] as $key) {
    $metrics[$key]['net_profit'] = $metrics[$key]['profit'] - $metrics[$key]['expenses'];
}

// Chart arrays
$chart_expenses = [];
$chart_net_profit = [];
foreach ($agg_by_date as $k => $v) {
    $chart_sales[]  = (float)$v['sales'];
    $chart_profit[] = (float)$v['profit'];
    $chart_expenses[] = (float)$v['expenses'];
    $chart_net_profit[] = (float)$v['net_profit'];
}

// Compare settings (user-triggered)
$compare_enabled = isset($_GET['compare']) && (string) wp_unslash($_GET['compare']) === '1';
$compare_mode = isset($_GET['compare_mode']) ? sanitize_text_field(wp_unslash((string)$_GET['compare_mode'])) : 'previous';
if (!in_array($compare_mode, ['previous', 'custom'], true)) {
    $compare_mode = 'previous';
}

// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized per-item below
$compare_metrics = isset($_GET['compare_metrics']) ? array_map('sanitize_text_field', wp_unslash((array) $_GET['compare_metrics'])) : ['sales', 'profit', 'expenses', 'net_profit'];
$compare_metrics = array_values(array_unique(array_filter(array_map(function($m) {
    $m = sanitize_text_field((string) $m);
    return in_array($m, ['sales', 'profit', 'expenses', 'net_profit'], true) ? $m : null;
}, $compare_metrics))));
if (!$compare_metrics) {
    $compare_metrics = ['sales', 'profit', 'expenses', 'net_profit'];
}

$compare_custom_start = isset($_GET['compare_start_date']) ? sanitize_text_field(wp_unslash((string)$_GET['compare_start_date'])) : '';
$compare_custom_end = isset($_GET['compare_end_date']) ? sanitize_text_field(wp_unslash((string)$_GET['compare_end_date'])) : '';

// Date-range compare (current range vs previous or custom)
$compare = [
    'enabled' => (bool) $compare_enabled,
    'mode' => $compare_mode,
    'metrics' => $compare_metrics,
    'current' => [
        'sales' => array_sum($chart_sales),
        'profit' => array_sum($chart_profit),
        'expenses' => array_sum($chart_expenses),
        'net_profit' => array_sum($chart_net_profit),
    ],
    'previous' => ['sales' => 0.0, 'profit' => 0.0, 'expenses' => 0.0, 'net_profit' => 0.0],
    'previous_start' => null,
    'previous_end' => null,
];

if ($compare_enabled) {
    $range_days = (int) floor((strtotime($end_date) - strtotime($start_date)) / DAY_IN_SECONDS) + 1;
    if ($range_days <= 0) {
        $compare['enabled'] = false;
    } else {
        if ($compare_mode === 'custom' && $compare_custom_start && $compare_custom_end) {
            $prev_start = $compare_custom_start;
            $prev_end = $compare_custom_end;
            if (strtotime($prev_start) > strtotime($prev_end)) {
                $tmp = $prev_start;
                $prev_start = $prev_end;
                $prev_end = $tmp;
            }
        } else {
            $prev_end = wp_date('Y-m-d', strtotime($start_date . ' -1 day'));
            $prev_start = wp_date('Y-m-d', strtotime($prev_end . ' -' . ($range_days - 1) . ' days'));
        }

        $compare['previous_start'] = $prev_start;
        $compare['previous_end'] = $prev_end;

        $prev_expenses = bizmart_analytics_get_expenses_range($prev_start, $prev_end);

        $prev_sales = 0.0;
        $prev_profit = 0.0;
        if ($bizmart_wc_active) {
            $prev_orders = bizmart_analytics_get_orders_range($prev_start, $prev_end);
            foreach ($prev_orders as $order) {
                if ($order instanceof WC_Order_Refund) continue;
                $prev_sales += (float) $order->get_total();

                foreach ($order->get_items() as $item) {
                    $product = $item->get_product();
                    if (!$product) continue;
                    $pid = $product->get_id();
                    $qty = (int) $item->get_quantity();
                    $item_total = (float) $item->get_total();

                    $pp = bizmart_analytics_get_purchase_price($pid);
                    if ($pp === null && $product->is_type('variation')) {
                        $parent_id = (int) $product->get_parent_id();
                        if ($parent_id) {
                            $pp = bizmart_analytics_get_purchase_price($parent_id);
                        }
                    }
                    $cost = ($pp !== null) ? ((float)$pp * (float)$qty) : 0.0;
                    $prev_profit += ($item_total - $cost);
                }
            }
        }

        $prev_exp_total = 0.0;
        if (is_array($prev_expenses)) {
            foreach ($prev_expenses as $e) {
                $prev_exp_total += (float) ($e->amount ?? 0);
            }
        }

        $compare['previous'] = [
            'sales' => $prev_sales,
            'profit' => $prev_profit,
            'expenses' => $prev_exp_total,
            'net_profit' => $prev_profit - $prev_exp_total,
        ];
    }
}

// Sorting: top products/by sales & profit
$products_by_sales  = array_values($products_agg);
$products_by_profit = array_values($products_agg);
usort($products_by_sales,  fn($a,$b) => $b['sales']  <=> $a['sales']);
usort($products_by_profit, fn($a,$b) => $b['profit'] <=> $a['profit']);
$top_products        = array_slice($products_by_sales, 0, 5);
$top_profit_products = array_slice($products_by_profit, 0, 5);

// Sort orders by total desc
usort($orders_list, fn($a,$b) => $b['total'] <=> $a['total']);

// Currency
$currency = $bizmart_wc_active ? get_woocommerce_currency() : (function_exists('bizmart_get_option') ? bizmart_get_option('biz_default_currency', '') : '');

// UI helpers
if (!function_exists('bizmart_analytics_margin_pct')) {
    function bizmart_analytics_margin_pct($profit, $sales) {
        return ($sales > 0) ? round(($profit / $sales) * 100, 2) : null;
    }
}
?>
<?php
// Enqueue Chart.js FIRST so dashboard JS dependency resolves properly
if (!wp_script_is('bizmart-chartjs', 'enqueued')) {
    wp_enqueue_script('bizmart-chartjs', BIZMART_CORE_URL . 'assets/vendor/chart.umd.min.js', [], '4.0.0', true);
    wp_enqueue_script('bizmart-chartjs-zoom', BIZMART_CORE_URL . 'assets/vendor/chartjs-plugin-zoom.min.js', ['bizmart-chartjs'], '2.0.0', true);
}

// Enqueue dashboard JS (extracted from inline scripts)
wp_enqueue_script(
    'bizmart-dashboard-js',
    BIZMART_CORE_URL . 'assets/admin-dashboard.js',
    ['jquery', 'bizmart-chartjs'],
    BIZMART_CORE_VERSION,
    true
);
wp_localize_script('bizmart-dashboard-js', 'BizmartDashConfig', [
    'ajax_url'   => admin_url('admin-ajax.php'),
    'nonce'      => wp_create_nonce('bizmart-analytics-nonce'),
    'currency'   => $currency,
    'admin_lang' => bizmart_admin_lang(),
    'chart'      => [
        'labels'     => $chart_labels,
        'sales'      => $chart_sales,
        'profit'     => $chart_profit,
        'expenses'   => $chart_expenses,
        'net_profit' => $chart_net_profit,
    ],
]);
?>
<div id="biz-analytics-dashboard" class="biz-quick-products">
    <!-- Styles moved to assets/admin.css for proper caching -->

    <?php if ($dashboard_data_error): ?>
    <div class="notice notice-warning" style="margin:12px 0;">
        <p><strong><?php echo esc_html(bizmart_text(
            'Some analytics data could not be loaded. The numbers below may be incomplete — please try refreshing the page.',
            'Certaines données analytiques n\'ont pas pu être chargées. Les chiffres ci-dessous peuvent être incomplets — veuillez actualiser la page.',
            'تعذر تحميل بعض بيانات التحليلات. قد تكون الأرقام أدناه غير مكتملة — يرجى تحديث الصفحة.'
        )); ?></strong></p>
    </div>
    <?php endif; ?>

    <div class="biz-dashboard">
        <!-- Enhanced Header -->
        <div class="biz-header" style="text-align: center; position: relative;">
            <h1 style="color: #ffffff; margin: 0 auto;">📊 <?php echo esc_html(bizmart_text('Dashboard', 'Tableau de bord', 'لوحة التحكم')); ?> — <span style="font-weight:400; opacity:0.85;"><?php echo defined('BIZMART_ADDON_VERSION') ? 'Bizmart Premium' : 'Bizmart Free'; ?></span></h1>
            <p style="margin: 8px auto 0;"><?php echo esc_html(bizmart_text('Complete overview of your sales, profit, and performance', "Vue d'ensemble complète de vos ventes, profits et performances", 'نظرة شاملة على مبيعاتك وأرباحك وأدائك')); ?></p>
            
        </div>

        <div class="biz-flex" style="margin-bottom:24px;">
            <div>
                <h2 style="margin:0;font-size:20px;color:#1f2937;"><?php echo esc_html(bizmart_text('Key metrics', 'Métriques clés', 'المؤشرات الرئيسية')); ?></h2>
                <p style="margin:4px 0 0;color:#6b7280;font-size:14px;"><?php echo esc_html(bizmart_text('Real-time performance', 'Performances en temps réel', 'الأداء في الوقت الفعلي')); ?></p>
            </div>
            <div style="display:flex; flex-direction:column; align-items:flex-start; gap:10px;">
                <div style="display:flex; gap:10px; align-items:center; justify-content:flex-start; flex-wrap:wrap;">
                <form method="GET" style="display: inline-flex; gap: 8px; align-items: center; flex-wrap:wrap;">
                    <input type="hidden" name="page" value="bizmart">
                    <input type="date" name="start_date" value="<?php echo esc_attr($start_date); ?>" style="padding: 8px 12px; border-radius: 8px; border: 1px solid #d1d5db; font-size: 14px;">
                    <span style="color:#6b7280;"><?php echo esc_html(bizmart_text('to', 'à', 'إلى')); ?></span>
                    <input type="date" name="end_date" value="<?php echo esc_attr($end_date); ?>" style="padding: 8px 12px; border-radius: 8px; border: 1px solid #d1d5db; font-size: 14px;">
                    <button type="submit" class="biz-btn" style="padding: 8px 16px;"><?php echo esc_html(bizmart_text('Filter', 'Filtrer', 'تصفية')); ?></button>

                    <?php if ($compare_enabled): ?>
                        <input type="hidden" name="compare" value="1">
                        <input type="hidden" name="compare_mode" value="<?php echo esc_attr($compare_mode); ?>">
                        <?php if (!empty($compare_custom_start)): ?>
                            <input type="hidden" name="compare_start_date" value="<?php echo esc_attr($compare_custom_start); ?>">
                        <?php endif; ?>
                        <?php if (!empty($compare_custom_end)): ?>
                            <input type="hidden" name="compare_end_date" value="<?php echo esc_attr($compare_custom_end); ?>">
                        <?php endif; ?>
                        <?php if (!empty($compare_metrics) && is_array($compare_metrics)): ?>
                            <?php foreach ($compare_metrics as $cm): ?>
                                <input type="hidden" name="compare_metrics[]" value="<?php echo esc_attr($cm); ?>">
                            <?php endforeach; ?>
                        <?php endif; ?>
                    <?php endif; ?>
                </form>

                <div class="biz-compare-dd" style="position:relative; display:inline-block;">
                    <button type="button" class="biz-btn" id="biz-compare-toggle" aria-expanded="false" style="padding: 8px 16px; background:#111827;"><?php echo esc_html(bizmart_text('Compare', 'Comparer', 'مقارنة')); ?> ▾</button>
                    <div id="biz-compare-panel" style="display:none; position:absolute; right:0; top:42px; width:min(720px, 92vw); background:#fff; border:1px solid #e5e7eb; border-radius:12px; box-shadow: 0 12px 30px rgba(0,0,0,0.14); padding:12px; z-index:999;">
                        <form method="GET" id="biz-compare-form" style="display:flex; gap:10px; flex-wrap:wrap; align-items:end;">
                            <input type="hidden" name="page" value="bizmart">
                            <input type="hidden" name="start_date" id="biz-compare-start" value="<?php echo esc_attr($start_date); ?>">
                            <input type="hidden" name="end_date" id="biz-compare-end" value="<?php echo esc_attr($end_date); ?>">
                            <input type="hidden" name="compare" value="1">

                            <div>
                                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;"><?php echo esc_html(bizmart_text('Compare with', 'Comparer avec', 'مقارنة مع')); ?></div>
                                <label style="display:block; font-size:13px; color:#111827;"><input type="radio" name="compare_mode" value="previous" <?php checked($compare_mode, 'previous'); ?>> <?php echo esc_html(bizmart_text('Previous period', 'Période précédente', 'الفترة السابقة')); ?></label>
                                <label style="display:block; font-size:13px; color:#111827;"><input type="radio" name="compare_mode" value="custom" <?php checked($compare_mode, 'custom'); ?>> <?php echo esc_html(bizmart_text('Custom range', 'Période personnalisée', 'فترة مخصصة')); ?></label>
                            </div>

                            <div id="biz-compare-custom" style="min-width:260px;">
                                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;"><?php echo esc_html(bizmart_text('Custom dates', 'Dates personnalisées', 'تواريخ مخصصة')); ?></div>
                                <div style="display:flex; gap:8px;">
                                    <input type="date" name="compare_start_date" value="<?php echo esc_attr($compare_custom_start); ?>" style="padding: 8px 10px; border-radius: 8px; border: 1px solid #d1d5db; font-size: 14px;">
                                    <input type="date" name="compare_end_date" value="<?php echo esc_attr($compare_custom_end); ?>" style="padding: 8px 10px; border-radius: 8px; border: 1px solid #d1d5db; font-size: 14px;">
                                </div>
                            </div>

                            <div style="min-width:260px;">
                                <div style="font-size:12px; color:#6b7280; margin-bottom:4px;"><?php echo esc_html(bizmart_text('Metrics', 'Indicateurs', 'المؤشرات')); ?></div>
                                <?php
                                    $m_all = ['sales' => bizmart_text('Sales', 'Ventes', 'المبيعات'), 'profit' => bizmart_text('Profit', 'Profit', 'الربح'), 'expenses' => bizmart_text('Expenses', 'Dépenses', 'المصاريف'), 'net_profit' => bizmart_text('Net profit', 'Profit net', 'صافي الربح')];
                                    foreach ($m_all as $mk => $mlabel):
                                ?>
                                    <label style="margin-right:10px; font-size:13px; color:#111827;"><input type="checkbox" name="compare_metrics[]" value="<?php echo esc_attr($mk); ?>" <?php checked(in_array($mk, $compare_metrics, true)); ?>> <?php echo esc_html($mlabel); ?></label>
                                <?php endforeach; ?>
                            </div>

                            <div style="display:flex; gap:8px; margin-left:auto;">
                                <button type="submit" class="button button-primary"><?php echo esc_html(bizmart_text('Apply', 'Appliquer', 'تطبيق')); ?></button>
                                <a class="button" href="<?php echo esc_url(remove_query_arg(['compare','compare_mode','compare_start_date','compare_end_date','compare_metrics'])); ?>"><?php echo esc_html(bizmart_text('Clear', 'Effacer', 'مسح')); ?></a>
                            </div>
                        </form>
                    </div>
                </div>
                </div>

                <?php
                    // Quick range chips: behave like the main filter.
                    // If compare is enabled, keep compare settings; otherwise remove them.
                    $chip_base = remove_query_arg(['start_date','end_date']);
                    if (!$compare_enabled) {
                        $chip_base = remove_query_arg([
                            'compare','compare_mode','compare_start_date','compare_end_date','compare_metrics',
                        ], $chip_base);
                    }
                ?>
                <div class="biz-chip-row" style="display:flex; gap:8px; flex-wrap:wrap; justify-content:flex-start; margin-top:-2px;">
                    <a class="biz-chip" href="<?php echo esc_url(add_query_arg('range','7', $chip_base)); ?>"><?php echo esc_html(bizmart_text('7 days', '7 jours', '7 أيام')); ?></a>
                    <a class="biz-chip" href="<?php echo esc_url(add_query_arg('range','30', $chip_base)); ?>"><?php echo esc_html(bizmart_text('30 days', '30 jours', '30 يومًا')); ?></a>
                    <a class="biz-chip" href="<?php echo esc_url(add_query_arg('range','all', $chip_base)); ?>"><?php echo esc_html(bizmart_text('Since the beginning', 'Depuis le début', 'منذ البداية')); ?></a>
                </div>
            </div>
        </div>

        <?php if (!empty($compare['enabled']) && !empty($compare['previous_start']) && !empty($compare['previous_end']) && !empty($compare['metrics'])): ?>
        <?php
            $fmt_delta = function($cur, $prev) {
                $delta = (float)$cur - (float)$prev;
                $sign = ($delta > 0) ? '+' : '';
                if ((float)$prev === 0.0) {
                    return $sign . number_format($delta, 2);
                }
                $pct = (($delta) / abs((float)$prev)) * 100;
                return $sign . number_format($delta, 2) . ' (' . $sign . number_format($pct, 1) . '%)';
            };
            $current_label = date_i18n('d/m/Y', strtotime($start_date)) . ' → ' . date_i18n('d/m/Y', strtotime($end_date));
            $prev_label = date_i18n('d/m/Y', strtotime($compare['previous_start'])) . ' → ' . date_i18n('d/m/Y', strtotime($compare['previous_end']));
        ?>
        <div class="biz-panel" style="margin-top:0; margin-bottom: 24px;">
            <div class="biz-flex" style="margin-bottom:12px;">
                <h3 style="margin:0;font-size:18px;color:#1f2937;">🔁 <?php echo esc_html(bizmart_text('Date Range Compare', 'Comparaison de période', 'مقارنة الفترات')); ?></h3>
                <div class="biz-small" style="color:#6b7280;">
                    <?php echo esc_html(bizmart_text('Current:', 'Actuelle :', 'الحالية:')); ?> <?php echo esc_html($current_label); ?>
                    &nbsp;•&nbsp;
                    <?php echo esc_html(bizmart_text('Previous:', 'Précédente :', 'السابقة:')); ?> <?php echo esc_html($prev_label); ?>
                </div>
            </div>
            <div class="biz-row" style="margin-bottom:0;">
                <?php if (in_array('sales', $compare['metrics'], true)): ?>
                <div class="biz-card">
                    <div class="biz-label"><?php echo esc_html(bizmart_text('Sales Δ', 'Ventes Δ', 'المبيعات Δ')); ?></div>
                    <div class="biz-value"><?php echo esc_html($fmt_delta($compare['current']['sales'], $compare['previous']['sales'])); ?></div>
                    <div class="biz-small"><?php echo esc_html(bizmart_text('Current:', 'Actuelle :', 'الحالية:')); ?> <?php echo bizmart_dash_money($compare['current']['sales']); ?></div>
                </div>
                <?php endif; ?>
                <?php if (in_array('profit', $compare['metrics'], true)): ?>
                <div class="biz-card">
                    <div class="biz-label"><?php echo esc_html(bizmart_text('Profit Δ', 'Profit Δ', 'الربح Δ')); ?></div>
                    <div class="biz-value"><?php echo esc_html($fmt_delta($compare['current']['profit'], $compare['previous']['profit'])); ?></div>
                    <div class="biz-small"><?php echo esc_html(bizmart_text('Current:', 'Actuelle :', 'الحالية:')); ?> <?php echo bizmart_dash_money($compare['current']['profit']); ?></div>
                </div>
                <?php endif; ?>
                <?php if (in_array('expenses', $compare['metrics'], true)): ?>
                <div class="biz-card">
                    <div class="biz-label"><?php echo esc_html(bizmart_text('Expenses Δ', 'Dépenses Δ', 'المصاريف Δ')); ?></div>
                    <div class="biz-value"><?php echo esc_html($fmt_delta($compare['current']['expenses'], $compare['previous']['expenses'])); ?></div>
                    <div class="biz-small"><?php echo esc_html(bizmart_text('Current:', 'Actuelle :', 'الحالية:')); ?> <?php echo bizmart_dash_money($compare['current']['expenses']); ?></div>
                </div>
                <?php endif; ?>
                <?php if (in_array('net_profit', $compare['metrics'], true)): ?>
                <div class="biz-card">
                    <div class="biz-label"><?php echo esc_html(bizmart_text('Net Profit Δ', 'Profit net Δ', 'صافي الربح Δ')); ?></div>
                    <div class="biz-value"><?php echo esc_html($fmt_delta($compare['current']['net_profit'], $compare['previous']['net_profit'])); ?></div>
                    <div class="biz-small"><?php echo esc_html(bizmart_text('Current:', 'Actuelle :', 'الحالية:')); ?> <?php echo bizmart_dash_money($compare['current']['net_profit']); ?></div>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Today's metrics with gradient cards -->
        <?php if (!$bizmart_wc_active): ?>
            <div class="notice notice-warning" style="margin: 0 0 16px;">
                <p style="margin: 8px 12px;">
                    <?php echo esc_html(bizmart_text('WooCommerce is not active. Sales/profit widgets will show 0 until WooCommerce is enabled.', 'WooCommerce n\'est pas actif. Les widgets ventes/profit afficheront 0 jusqu\'à activation de WooCommerce.', 'WooCommerce غير مفعّل. ستعرض مؤشرات المبيعات/الربح 0 حتى يتم تفعيل WooCommerce.')); ?>
                </p>
            </div>
        <?php endif; ?>

        <div class="biz-stats-grid">
            <div class="biz-stat-card" title="<?php echo esc_attr(bizmart_text("Total sales made today", "Ventes totales réalisées aujourd'hui", "إجمالي مبيعات اليوم")); ?>">
                <div class="biz-stat-value"><?php echo bizmart_dash_money($metrics['today']['sales']); ?></div>
                <div class="biz-stat-label"><?php echo esc_html(bizmart_text("Today's sales", "Ventes aujourd'hui", "مبيعات اليوم")); ?></div>
            </div>
            <div class="biz-stat-card positive" title="<?php echo esc_attr(bizmart_text('Net profit calculated today (sales - costs)', "Profit net calculé aujourd'hui (ventes - coûts)", 'صافي الربح المحسوب اليوم (المبيعات - التكاليف)')); ?>">
                <div class="biz-stat-value"><?php echo bizmart_dash_money($metrics['today']['profit']); ?></div>
                <div class="biz-stat-label"><?php echo esc_html(bizmart_text("Today's profit", "Profit aujourd'hui", "ربح اليوم")); ?></div>
            </div>
            <div class="biz-stat-card" style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);" title="<?php echo esc_attr(bizmart_text('Total Products & Stock', 'Total Produits & Stock', 'إجمالي المنتجات والمخزون')); ?>">
                <div class="biz-stat-label">
                    <div style="font-weight: 700; text-transform: uppercase; font-size: 13px; margin-bottom: 6px; letter-spacing: 0.5px;"><?php echo esc_html(bizmart_text('Products & Stock', 'Produits & Stock', 'المنتجات والمخزون')); ?></div>
                    <div style="font-size: 16px; font-weight: 700; margin-bottom: 4px;">
                        <?php echo intval($total_products); ?> <?php echo esc_html(bizmart_text('articles', 'articles', 'منتج')); ?> / <?php echo number_format((float)($inv_totals['total_stock_qty'] ?? 0)); ?> <?php echo esc_html(bizmart_text('in stock', 'en stock', 'في المخزون')); ?>
                    </div>
                    <?php if ($missing_purchase_price_count > 0): ?>
                        <div style="margin-top: 6px; padding-top: 6px; border-top: 1px solid rgba(255,255,255,0.2);">
                            <button onclick="openMissingPricesPopup()" style="background: rgba(239, 68, 68, 0.9); color: white; border: none; padding: 5px 10px; border-radius: 6px; font-size: 11px; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; transition: all 0.2s;" onmouseover="this.style.background='rgba(239, 68, 68, 1)'; this.style.transform='scale(1.05)';" onmouseout="this.style.background='rgba(239, 68, 68, 0.9)'; this.style.transform='scale(1)';">
                                <span style="font-size: 13px;">⚠️</span> <?php echo intval($missing_purchase_price_count); ?> <?php echo esc_html(bizmart_text('missing', 'manquants', 'ناقص')); ?>
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="biz-stat-card neutral" title="<?php echo esc_attr(bizmart_text('Stock Value Details', 'Détails Valeur Stock', 'تفاصيل قيمة المخزون')); ?>">
                <div class="biz-stat-label">
                    <div style="font-weight: 700; text-transform: uppercase; font-size: 13px; margin-bottom: 6px; letter-spacing: 0.5px;"><?php echo esc_html(bizmart_text('Stock Value', 'Valeur du Stock', 'قيمة المخزون')); ?></div>
                    <div><?php echo esc_html(bizmart_text('Vente:', 'Vente :', 'البيع:')); ?> <strong><?php echo bizmart_dash_money($stock_value); ?></strong></div>
                    <div><?php echo esc_html(bizmart_text('Achat:', 'Achat :', 'الشراء:')); ?> <strong><?php echo bizmart_dash_money($stock_purchase_value); ?></strong></div>
                </div>
            </div>
        </div>

        <!-- Period metrics with enhanced cards -->
        <div class="biz-row">
            <div class="biz-card">
                <div class="biz-label"><?php echo esc_html(bizmart_text('This week', 'Cette semaine', 'هذا الأسبوع')); ?></div>
                <div class="biz-value"><?php echo bizmart_dash_money($metrics['week']['sales']); ?></div>
                <div class="biz-small"><?php echo esc_html(bizmart_text('Profit:', 'Profit :', 'الربح:')); ?> <?php echo bizmart_dash_money($metrics['week']['profit']); ?> | <?php echo esc_html(bizmart_text('Orders:', 'Commandes :', 'الطلبات:')); ?> <?php echo intval($metrics['week']['orders']); ?></div>
            </div>
            <div class="biz-card">
                <div class="biz-label"><?php echo esc_html(bizmart_text('This month', 'Ce mois', 'هذا الشهر')); ?></div>
                <div class="biz-value"><?php echo bizmart_dash_money($metrics['month']['sales']); ?></div>
                <div class="biz-small"><?php echo esc_html(bizmart_text('Profit:', 'Profit :', 'الربح:')); ?> <?php echo bizmart_dash_money($metrics['month']['profit']); ?> | <?php echo esc_html(bizmart_text('Orders:', 'Commandes :', 'الطلبات:')); ?> <?php echo intval($metrics['month']['orders']); ?></div>
            </div>
            <div class="biz-card">
                <div class="biz-label"><?php echo esc_html(bizmart_text('This year', 'Cette année', 'هذه السنة')); ?></div>
                <div class="biz-value"><?php echo bizmart_dash_money($metrics['year']['sales']); ?></div>
                <div class="biz-small"><?php echo esc_html(bizmart_text('Profit:', 'Profit :', 'الربح:')); ?> <?php echo bizmart_dash_money($metrics['year']['profit']); ?> | <?php echo esc_html(bizmart_text('Orders:', 'Commandes :', 'الطلبات:')); ?> <?php echo intval($metrics['year']['orders']); ?></div>
            </div>
            <div class="biz-card">
                <div class="biz-label"><?php echo esc_html(bizmart_text('Since the beginning', 'Depuis le début', 'منذ البداية')); ?></div>
                <div class="biz-value"><?php echo bizmart_dash_money($metrics['all']['sales']); ?></div>
                <div class="biz-small"><?php echo esc_html(bizmart_text('Profit:', 'Profit :', 'الربح:')); ?> <?php echo bizmart_dash_money($metrics['all']['profit']); ?> | <?php echo esc_html(bizmart_text('Orders:', 'Commandes :', 'الطلبات:')); ?> <?php echo intval($metrics['all']['orders']); ?></div>
            </div>
        </div>

        <!-- Chart Panel -->
        <div class="biz-panel">
            <div style="margin-bottom:20px;">
                <h3 style="margin:0;font-size:20px;color:#1f2937;">📈 <?php echo esc_html(bizmart_text('Sales & profit trend', 'Évolution des ventes & profits', 'اتجاه المبيعات والأرباح')); ?></h3>
                <p style="margin:4px 0 0;color:#6b7280;font-size:14px;">
                    <?php
                        if (!empty($start_date_param) && !empty($end_date_param)) {
                            echo esc_html(bizmart_text('From ', 'Du ', 'من ')) . esc_html(date_i18n('d M Y', strtotime($start_date))) . esc_html(bizmart_text(' to ', ' au ', ' إلى ')) . esc_html(date_i18n('d M Y', strtotime($end_date)));
                        } else {
                            echo esc_html(
                                ($range === '7')
                                    ? bizmart_text('Last 7 days', '7 derniers jours', 'آخر 7 أيام')
                                    : (($range === '30') ? bizmart_text('Last 30 days', '30 derniers jours', 'آخر 30 يومًا') : bizmart_text('Since the beginning', 'Depuis le début', 'منذ البداية'))
                            );
                        }
                    ?>
                </p>
            </div>
            <div style="height:350px; margin-top:12px;">
                <canvas id="bizChart"></canvas>
            </div>
        </div>

        <!-- Top Products -->
            <div id="biz-top-products-panel" class="biz-panel">
            <div style="margin-bottom:20px;">
                <h3 style="margin:0;font-size:20px;color:#1f2937;">🏆 <?php echo esc_html(bizmart_text('Top 5 best sellers', 'Top 5 des meilleures ventes', 'أفضل 5 مبيعًا')); ?></h3>
                <p style="margin:4px 0 0;color:#6b7280;font-size:14px;"><?php echo esc_html(bizmart_text('Best performing products by sales volume', 'Produits les plus performants par volume de ventes', 'المنتجات الأفضل أداءً حسب حجم المبيعات')); ?></p>
            </div>
            <div id="biz-top-products-scroll" class="biz-scroll" style="padding-right:8px; scroll-behavior: smooth;">
            <table id="biz-top-products-table" class="biz-table">
                <thead>
                    <tr>
                        <th><?php echo esc_html(bizmart_text('Product', 'Produit', 'المنتج')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Quantity', 'Quantité', 'الكمية')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Sales', 'Ventes', 'المبيعات')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Profit', 'Profit', 'الربح')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Margin %', 'Marge %', 'الهامش %')); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($top_products)): ?>
                        <tr><td colspan="5" style="text-align:center;padding:32px;color:#9ca3af;font-size:14px;">📦 <?php echo esc_html(bizmart_text('No sales data yet. Top sellers will appear once orders are placed.', 'Aucune donnée de vente. Les meilleurs vendeurs apparaîtront une fois les commandes passées.', 'لا توجد بيانات مبيعات بعد. ستظهر المنتجات الأكثر مبيعًا بعد تسجيل الطلبات.')); ?></td></tr>
                    <?php else: ?>
                    <?php foreach ($top_products as $p): ?>
                        <tr>
                            <td><a href="#" onclick="openProductPopup(<?php echo intval($p['id']); ?>)" style="color:#4f46e5;text-decoration:none;font-weight:500;"><?php echo esc_html($p['name']); ?></a></td>
                            <td><?php echo intval($p['qty']); ?></td>
                            <td><?php echo bizmart_dash_money($p['sales']); ?></td>
                            <td><?php echo bizmart_dash_money($p['profit']); ?></td>
                            <td><?php $m=bizmart_analytics_margin_pct($p['profit'],$p['sales']); echo ($m!==null? esc_html($m).'%' : '—'); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            </div>
        </div>

        <!-- Most Profitable Products -->
        <div class="biz-panel">
            <div style="margin-bottom:20px;">
                <h3 style="margin:0;font-size:20px;color:#1f2937;">💰 <?php echo esc_html(bizmart_text('Top 5 most profitable', 'Top 5 des plus profitables', 'أفضل 5 ربحًا')); ?></h3>
                <p style="margin:4px 0 0;color:#6b7280;font-size:14px;"><?php echo esc_html(bizmart_text('Products generating the highest profit', 'Produits générant le plus de marge bénéficiaire', 'المنتجات التي تحقق أعلى ربح')); ?></p>
            </div>
            <table class="biz-table">
                <thead>
                    <tr>
                        <th><?php echo esc_html(bizmart_text('Product', 'Produit', 'المنتج')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Quantity', 'Quantité', 'الكمية')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Sales', 'Ventes', 'المبيعات')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Profit', 'Profit', 'الربح')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Margin %', 'Marge %', 'الهامش %')); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($top_profit_products)): ?>
                        <tr><td colspan="5" style="text-align:center;padding:32px;color:#9ca3af;font-size:14px;">💰 <?php echo esc_html(bizmart_text('No profit data yet. Most profitable products will appear once orders are placed.', 'Aucune donnée de profit. Les produits les plus profitables apparaîtront une fois les commandes passées.', 'لا توجد بيانات أرباح بعد. ستظهر المنتجات الأكثر ربحًا بعد تسجيل الطلبات.')); ?></td></tr>
                    <?php else: ?>
                    <?php foreach ($top_profit_products as $p): ?>
                        <tr>
                            <td><a href="#" onclick="openProductPopup(<?php echo intval($p['id']); ?>)" style="color:#4f46e5;text-decoration:none;font-weight:500;"><?php echo esc_html($p['name']); ?></a></td>
                            <td><?php echo intval($p['qty']); ?></td>
                            <td><?php echo bizmart_dash_money($p['sales']); ?></td>
                            <td><?php echo bizmart_dash_money($p['profit']); ?></td>
                            <td><?php $m=bizmart_analytics_margin_pct($p['profit'],$p['sales']); echo ($m!==null? esc_html($m).'%' : '—'); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Recent Orders -->
        <div class="biz-panel">
            <div style="margin-bottom:20px;">
                <h3 style="margin:0;font-size:20px;color:#1f2937;">📋 <?php echo esc_html(bizmart_text('Recent orders', 'Commandes récentes', 'الطلبات الأخيرة')); ?></h3>
                <p style="margin:4px 0 0;color:#6b7280;font-size:14px;"><?php echo esc_html(bizmart_text('Latest transactions sorted by amount', 'Dernières transactions triées par montant', 'آخر المعاملات مرتبة حسب المبلغ')); ?></p>
            </div>
                <div class="biz-flex" style="margin-bottom:12px; display:flex; justify-content:space-between; align-items:center; gap:12px;">
                    <div style="flex:1;">
                        <input type="text" id="biz-orders-search" placeholder="<?php echo esc_attr(bizmart_text('🔍 Search by order number...', '🔍 Rechercher par numéro de commande...', '🔍 البحث برقم الطلب...')); ?>" style="width:100%; max-width:300px; padding:8px 12px; border:1px solid #d1d5db; border-radius:8px; font-size:14px;">
                    </div>
                    <div>
                        <button id="biz-recent-toggle" class="biz-btn biz-btn-secondary" style="display:none;"><?php echo esc_html(bizmart_text('Show all', 'Afficher tout', 'عرض الكل')); ?></button>
                    </div>
                </div>

                <div id="biz-recent-orders-scroll" class="biz-scroll" style="padding-right:8px; scroll-behavior: smooth;">
                    <table id="biz-recent-orders-table" class="biz-table biz-table-compact">
                        <thead>
                            <tr>
                                <th style="width:40%"><?php echo esc_html(bizmart_text('Order', 'Commande', 'الطلب')); ?></th>
                                <th style="width:20%"><?php echo esc_html(bizmart_text('Date', 'Date', 'التاريخ')); ?></th>
                                <th style="width:20%"><?php echo esc_html(bizmart_text('Total', 'Total', 'الإجمالي')); ?></th>
                                <th style="width:20%"><?php echo esc_html(bizmart_text('Profit', 'Profit', 'الربح')); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($orders_list)): ?>
                                <tr><td colspan="4" style="text-align:center;padding:32px;color:#9ca3af;font-size:14px;">📋 <?php echo esc_html(bizmart_text('No orders in this period. Orders will appear here once customers make purchases.', 'Aucune commande sur cette période. Les commandes apparaîtront une fois les achats effectués.', 'لا توجد طلبات في هذه الفترة. ستظهر الطلبات بعد إتمام عمليات الشراء.')); ?></td></tr>
                            <?php else: ?>
                            <?php foreach ($orders_list as $o): ?>
                                <tr>
                                    <td><a href="<?php echo esc_url($o['link']); ?>" style="color:#4f46e5;text-decoration:none;font-weight:500;">#<?php echo esc_html($o['number']); ?></a></td>
                                    <td><?php echo esc_html(date_i18n('d M Y', strtotime($o['date']))); ?></td>
                                    <td><?php echo bizmart_dash_money($o['total']); ?></td>
                                    <td><?php echo bizmart_dash_money($o['profit']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
        </div>

        <!-- v3.0: Price Alerts Notification Bar -->
        <?php
        $active_alerts = function_exists('bizmart_get_active_alerts') ? bizmart_get_active_alerts() : [];
        if (!empty($active_alerts)):
        ?>
        <div class="biz-panel" style="border: 1px solid #fbbf24; background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%); border-radius:12px;">
            <div style="display:flex; align-items:center; gap:12px; margin-bottom:12px;">
                <span style="font-size:24px;">🔔</span>
                <div>
                    <h3 style="margin:0;font-size:18px;color:#92400e;"><?php echo esc_html(bizmart_text('Price Alerts', 'Alertes de Prix', 'تنبيهات الأسعار')); ?>
                        <span style="background:#fbbf24; color:#78350f; font-size:11px; padding:2px 8px; border-radius:8px; margin-left:6px;"><?php echo count($active_alerts); ?></span>
                    </h3>
                    <p style="margin:2px 0 0; font-size:13px; color:#a16207;"><?php echo esc_html(bizmart_text('Recent price changes & low margin warnings', 'Changements de prix récents et alertes de marge', 'تنبيهات تغير الأسعار وتحذيرات الهامش')); ?></p>
                </div>
                <button onclick="document.getElementById('biz-alerts-list').style.display = document.getElementById('biz-alerts-list').style.display === 'none' ? 'block' : 'none';" style="margin-left:auto; background:rgba(146,64,14,0.1); border:1px solid #d97706; color:#92400e; padding:6px 14px; border-radius:8px; cursor:pointer; font-size:13px; font-weight:500;">
                    <?php echo esc_html(bizmart_text('Toggle', 'Afficher/Masquer', 'عرض/إخفاء')); ?>
                </button>
            </div>
            <div id="biz-alerts-list" style="display:block;">
                <?php foreach ($active_alerts as $key => $alert): ?>
                <div style="display:flex; align-items:center; gap:10px; padding:10px 14px; background:#fff; border-radius:8px; margin-bottom:6px; border-left:4px solid <?php echo esc_attr($alert['type'] === 'low_margin' ? '#ef4444' : '#f59e0b'); ?>;">
                    <span style="font-size:18px;"><?php echo esc_html($alert['type'] === 'low_margin' ? '⚠️' : '📈'); ?></span>
                    <div style="flex:1;">
                        <?php if ($alert['type'] === 'low_margin'): ?>
                            <span style="font-weight:600; color:#991b1b;">
                                <?php echo esc_html($alert['name']); ?>
                            </span>
                            <span style="color:#6b7280; font-size:13px;">
                                — <?php echo esc_html(bizmart_text('Margin', 'Marge', 'هامش')); ?>: <span style="color:#dc2626; font-weight:600;"><?php echo esc_html($alert['margin']); ?>%</span>
                                (PP: <?php echo bizmart_dash_money($alert['pp']); ?>, SP: <?php echo bizmart_dash_money($alert['sp']); ?>)
                            </span>
                        <?php else: ?>
                            <span style="font-weight:600; color:#92400e;">
                                <?php echo esc_html($alert['name']); ?>
                            </span>
                            <span style="color:#6b7280; font-size:13px;">
                                — <?php echo esc_html(bizmart_text('Price changed', 'Prix modifié', 'تغير السعر')); ?> <?php echo esc_html($alert['direction']); ?><?php echo esc_html($alert['change_pct']); ?>%
                                (<?php echo bizmart_dash_money($alert['old_pp']); ?> → <?php echo bizmart_dash_money($alert['new_pp']); ?>)
                            </span>
                        <?php endif; ?>
                    </div>
                    <span style="font-size:11px; color:#9ca3af; white-space:nowrap;"><?php echo esc_html($alert['date'] ?? ''); ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- v3.0: P&L moved to Expenses page (addon) — only Low Margin panel remains on dashboard -->

        <!-- v3.0: Low Margin Alerts -->
        <?php
        $margin_threshold = (float) bizmart_get_option('biz_margin_alert_threshold', 10);
        $low_margin_products = function_exists('bizmart_get_low_margin_products') ? bizmart_get_low_margin_products($margin_threshold, 10) : [];
        if (!empty($low_margin_products)):
        ?>
        <div class="biz-panel" style="border: 1px solid #fecaca; background:#fff5f5;">
            <div style="margin-bottom:16px;">
                <h3 style="margin:0;font-size:20px;color:#991b1b;">⚠️ <?php echo esc_html(bizmart_text('Low Margin Products', 'Produits à Faible Marge', 'منتجات بهامش منخفض')); ?>
                    <span style="background:#fecaca; color:#991b1b; font-size:12px; padding:3px 8px; border-radius:6px; margin-left:8px;"><?php echo esc_html(bizmart_text('below', 'sous', 'أقل من')); ?> <?php echo esc_html($margin_threshold); ?>%</span>
                </h3>
            </div>
            <table class="biz-table">
                <thead>
                    <tr>
                        <th><?php echo esc_html(bizmart_text('Product', 'Produit', 'المنتج')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Purchase Price', "Prix d'Achat", 'سعر الشراء')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Selling Price', 'Prix de Vente', 'سعر البيع')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Margin %', 'Marge %', 'الهامش %')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Last Change', 'Dernier Changement', 'آخر تعديل')); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($low_margin_products as $lm): ?>
                    <tr>
                        <td>
                            <a href="#" onclick="openPriceHistoryModal(<?php echo intval($lm['product_id']); ?>); return false;" style="color:#4f46e5; text-decoration:none; font-weight:500;">
                                <?php echo esc_html($lm['name']); ?>
                            </a>
                        </td>
                        <td><?php echo bizmart_dash_money($lm['purchase_price']); ?></td>
                        <td><?php echo bizmart_dash_money($lm['selling_price']); ?></td>
                        <td>
                            <span style="background:<?php echo esc_attr($lm['margin_pct'] < 5 ? '#fecaca' : '#fed7aa'); ?>; color:<?php echo esc_attr($lm['margin_pct'] < 5 ? '#991b1b' : '#9a3412'); ?>; padding:3px 8px; border-radius:6px; font-weight:600; font-size:13px;">
                                <?php echo esc_html($lm['margin_pct']); ?>%
                            </span>
                        </td>
                        <td style="color:#6b7280; font-size:13px;"><?php echo esc_html($lm['last_change'] ? date_i18n('d M Y', strtotime($lm['last_change'])) : '—'); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

    </div>
</div>

<!-- Chart.js loaded via wp_enqueue_script above -->

<!-- Missing Purchase Prices Popup -->
<div id="biz-missing-prices-popup" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.6); z-index:99999; align-items:center; justify-content:center; padding:20px; backdrop-filter:blur(4px);">
    <div style="background:white; border-radius:16px; max-width:900px; width:100%; max-height:90vh; overflow:hidden; box-shadow:0 25px 50px -12px rgba(0,0,0,0.25); display:flex; flex-direction:column;">
        <!-- Header -->
        <div style="padding:24px; border-bottom:1px solid #e5e7eb; background:linear-gradient(135deg, #ef4444 0%, #dc2626 100%); color:white;">
            <div style="display:flex; justify-content:space-between; align-items:center;">
                <div>
                    <h2 style="margin:0; font-size:20px; font-weight:700; display:flex; align-items:center; gap:8px;">
                        <span style="font-size:24px;">⚠️</span>
                        <?php echo esc_html(bizmart_text('Products Missing Purchase Price', "Produits Sans Prix d'Achat", 'منتجات بدون سعر شراء')); ?>
                    </h2>
                    <p style="margin:4px 0 0; opacity:0.9; font-size:14px;"><?php echo esc_html(bizmart_text('Set purchase prices to enable accurate profit calculation', "Définir les prix d'achat pour calculer les profits", 'حدد أسعار الشراء لتفعيل حساب الربح بدقة')); ?></p>
                </div>
                <button onclick="closeMissingPricesPopup()" style="background:rgba(255,255,255,0.2); border:none; color:white; width:36px; height:36px; border-radius:8px; cursor:pointer; font-size:20px; font-weight:bold; transition:all 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.3)';" onmouseout="this.style.background='rgba(255,255,255,0.2)';">&times;</button>
            </div>
        </div>
        
        <!-- Content -->
        <div style="padding:24px; overflow-y:auto; flex:1;">
            <table class="biz-table" style="width:100%;">
                <thead>
                    <tr>
                        <th style="width:40%;"><?php echo esc_html(bizmart_text('Product', 'Produit', 'المنتج')); ?></th>
                        <th style="width:15%;"><?php echo esc_html(bizmart_text('SKU', 'SKU', 'رمز المنتج')); ?></th>
                        <th style="width:20%;"><?php echo esc_html(bizmart_text('Purchase Price', "Prix d'Achat", 'سعر الشراء')); ?></th>
                        <th style="width:25%;"><?php echo esc_html(bizmart_text('Action', 'Action', 'إجراء')); ?></th>
                    </tr>
                </thead>
                <tbody id="biz-missing-prices-tbody">
                    <?php foreach ($products_without_price as $ppp):
                        $is_variable = ($ppp['type'] === 'variable');
                        $var_ids = $ppp['variation_ids'] ?? [];
                    ?>
                    <tr id="biz-missing-row-<?php echo intval($ppp['id']); ?>">
                        <td>
                            <div style="font-weight:600; color:#111827;">
                                <?php echo esc_html($ppp['name']); ?>
                                <?php if ($is_variable): ?>
                                    <span style="background:#8b5cf6; color:white; font-size:10px; padding:2px 6px; border-radius:4px; margin-left:6px;"><?php echo esc_html(bizmart_text('Variable', 'Variable', 'متغير')); ?></span>
                                <?php endif; ?>
                            </div>
                            <?php if ($is_variable && !empty($var_ids)): ?>
                            <div style="margin-top:4px; font-size:12px; color:#6b7280;">
                                <?php echo count($var_ids); ?> <?php echo esc_html(bizmart_text('variations', 'variations', 'اختلافات')); ?>
                                — <a href="javascript:void(0)" onclick="toggleVariationRows(<?php echo intval($ppp['id']); ?>)" style="color:#4f46e5; text-decoration:none; font-weight:500;"><?php echo esc_html(bizmart_text('Show details', 'Voir détails', 'عرض التفاصيل')); ?></a>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <code style="background:#f3f4f6; padding:4px 8px; border-radius:6px; font-size:11px; font-weight:600; color:#4b5563;"><?php echo esc_html($ppp['sku'] ?: '—'); ?></code>
                        </td>
                        <td>
                            <input type="number" step="0.01" min="0" id="biz-price-input-<?php echo intval($ppp['id']); ?>" placeholder="0.00" style="width:100%; padding:8px 12px; border:1px solid #d1d5db; border-radius:8px; font-size:14px; transition:all 0.2s;" onfocus="this.style.borderColor='#3b82f6'; this.style.boxShadow='0 0 0 3px rgba(59,130,246,0.1)';" onblur="this.style.borderColor='#d1d5db'; this.style.boxShadow='none';">
                            <?php if ($is_variable): ?>
                            <label style="display:flex; align-items:center; gap:4px; margin-top:4px; font-size:11px; color:#6b7280; cursor:pointer;">
                                <input type="checkbox" id="biz-apply-all-vars-<?php echo intval($ppp['id']); ?>" checked style="margin:0;">
                                <?php echo esc_html(bizmart_text('Apply to all variations', 'Appliquer à toutes les variations', 'تطبيق على جميع المتغيرات')); ?>
                            </label>
                            <?php endif; ?>
                        </td>
                        <td>
                            <button onclick="saveQuickPrice(<?php echo intval($ppp['id']); ?>)" style="background:linear-gradient(135deg, #10b981 0%, #059669 100%); color:white; border:none; padding:8px 16px; border-radius:8px; font-size:13px; font-weight:600; cursor:pointer; transition:all 0.2s; width:100%;" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 12px rgba(16,185,129,0.3)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='none';">
                                <?php echo esc_html(bizmart_text('Save', 'Enregistrer', 'حفظ')); ?>
                            </button>
                        </td>
                    </tr>
                    <?php
                    // Render hidden variation sub-rows for variable products
                    if ($is_variable && !empty($var_ids)):
                        foreach ($var_ids as $vid):
                            $vproduct = wc_get_product($vid);
                            if (!$vproduct) continue;
                            $vp_price = (float) get_post_meta($vid, '_purchase_price', true);
                            if ($vp_price > 0) continue; // Already has price
                            $attrs = $vproduct->get_attributes();
                            $attr_parts = [];
                            foreach ($attrs as $aname => $aval) {
                                $attr_parts[] = ucwords(str_replace(['pa_','-'], ['',' '], $aname)) . ': ' . ucfirst(str_replace('-',' ', $aval));
                            }
                            $vlabel = !empty($attr_parts) ? implode(' | ', $attr_parts) : ('#' . $vid);
                    ?>
                    <tr class="biz-var-subrow biz-var-subrow-<?php echo intval($ppp['id']); ?>" style="display:none; background:#f9fafb;">
                        <td style="padding-left:28px;">
                            <div style="font-size:13px; color:#4b5563;">↳ <?php echo esc_html($vlabel); ?></div>
                        </td>
                        <td>
                            <code style="background:#f3f4f6; padding:2px 6px; border-radius:4px; font-size:10px; color:#6b7280;"><?php echo esc_html($vproduct->get_sku() ?: '—'); ?></code>
                        </td>
                        <td>
                            <input type="number" step="0.01" min="0" id="biz-price-input-<?php echo intval($vid); ?>" placeholder="0.00" style="width:100%; padding:6px 10px; border:1px solid #e5e7eb; border-radius:6px; font-size:13px;">
                        </td>
                        <td>
                            <button onclick="saveQuickPrice(<?php echo intval($vid); ?>)" style="background:#3b82f6; color:white; border:none; padding:6px 12px; border-radius:6px; font-size:12px; font-weight:600; cursor:pointer; width:100%;">
                                <?php echo esc_html(bizmart_text('Save', 'Enregistrer', 'حفظ')); ?>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; endif; ?>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php if (empty($products_without_price)): ?>
            <div style="text-align:center; padding:40px; color:#6b7280;">
                <div style="font-size:48px; margin-bottom:12px;">✅</div>
                <p style="font-size:16px; font-weight:600; margin:0;"><?php echo esc_html(bizmart_text('All products have purchase prices!', 'Tous les produits ont des prix d\'achat !', 'جميع المنتجات لديها أسعار شراء!')); ?></p>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Purchase Price Popup -->
<div id="biz-price-popup" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.45); z-index:9999; align-items:center; justify-content:center;"> 
    <div style="background:#fff; padding:20px; border-radius:10px; width:380px; max-width:92%; box-shadow:0 8px 30px rgba(0,0,0,0.2);">
        <h3 style="margin:0 0 8px 0; font-size:18px;"><?php echo esc_html(bizmart_text('Set purchase price', "Définir le prix d'achat", 'تحديد سعر الشراء')); ?></h3>
        <p id="biz-price-popup-product-name" style="margin:0 0 12px 0; font-weight:600; color:#374151;"></p>
        <label style="font-size:13px;color:#6b7280;"><?php echo esc_html(bizmart_text('Purchase price', "Prix d'achat", 'سعر الشراء')); ?></label>
        <input type="number" id="biz-price-popup-value" step="0.01" style="width:100%; padding:10px; margin-top:6px; border:1px solid #d1d5db; border-radius:6px;">
        <div style="display:flex; gap:8px; justify-content:flex-end; margin-top:14px;">
            <button class="biz-btn biz-btn-secondary" onclick="closePurchasePricePopup()"><?php echo esc_html(bizmart_text('Cancel', 'Annuler', 'إلغاء')); ?></button>
            <button class="biz-btn biz-btn-success" onclick="savePurchasePrice()"><?php echo esc_html(bizmart_text('Save', 'Enregistrer', 'حفظ')); ?></button>
        </div>
    </div>
</div>

<!-- Product Popup -->
<div id="biz-product-popup" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.45); z-index:9999; align-items:center; justify-content:center;"> 
    <div style="background:#fff; padding:20px; border-radius:10px; width:500px; max-width:92%; box-shadow:0 8px 30px rgba(0,0,0,0.2); max-height:80vh; overflow-y:auto;">
        <h3 id="biz-product-popup-title" style="margin:0 0 8px 0; font-size:18px;"></h3>
        <div id="biz-product-popup-content"></div>
        <div style="display:flex; gap:8px; justify-content:flex-end; margin-top:14px;">
            <button class="biz-btn" onclick="window.open(document.getElementById('biz-product-edit-link').href, '_blank')"><?php echo esc_html(bizmart_text('Edit in WooCommerce', 'Modifier dans WooCommerce', 'تعديل في WooCommerce')); ?></button>
            <button class="biz-btn biz-btn-secondary" onclick="closeProductPopup()"><?php echo esc_html(bizmart_text('Close', 'Fermer', 'إغلاق')); ?></button>
        </div>
    </div>
</div>

<!-- v3.0: Price History Modal -->
<div id="biz-price-history-modal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.55); z-index:99999; align-items:center; justify-content:center; padding:20px; backdrop-filter:blur(4px);">
    <div style="background:#fff; border-radius:16px; max-width:960px; width:100%; max-height:90vh; overflow:hidden; box-shadow:0 25px 50px -12px rgba(0,0,0,0.25); display:flex; flex-direction:column;">
        <div style="padding:24px; border-bottom:1px solid #e5e7eb; background:linear-gradient(135deg, #4f46e5, #7c3aed); color:white;">
            <div style="display:flex; justify-content:space-between; align-items:center;">
                <div>
                    <h2 id="biz-ph-title" style="margin:0; font-size:20px; font-weight:700;">📊 <?php echo esc_html(bizmart_text('Price History', 'Historique des Prix', 'سجل الأسعار')); ?></h2>
                    <div id="biz-ph-summary" style="margin:8px 0 0; font-size:14px; opacity:0.9;"></div>
                </div>
                <button onclick="closePriceHistoryModal()" style="background:rgba(255,255,255,0.2); border:none; color:white; width:36px; height:36px; border-radius:8px; cursor:pointer; font-size:20px;">&times;</button>
            </div>
        </div>
        <div style="padding:24px; overflow-y:auto; flex:1;">
            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap:12px; margin-bottom:20px;">
                <div style="background:#f0f9ff; padding:12px; border-radius:8px; text-align:center; border:1px solid #bae6fd;">
                    <div style="font-size:11px; color:#0369a1; font-weight:600; text-transform:uppercase;"><?php echo esc_html(bizmart_text('WAC (CUMP)', 'CUMP', 'المتوسط المرجح')); ?></div>
                    <div id="biz-ph-wac" style="font-size:18px; font-weight:700; color:#0c4a6e;">—</div>
                </div>
                <div style="background:#f0fdf4; padding:12px; border-radius:8px; text-align:center; border:1px solid #bbf7d0;">
                    <div style="font-size:11px; color:#166534; font-weight:600; text-transform:uppercase;"><?php echo esc_html(bizmart_text('Last PP', 'Dernier PA', 'آخر سعر شراء')); ?></div>
                    <div id="biz-ph-last-pp" style="font-size:18px; font-weight:700; color:#14532d;">—</div>
                </div>
                <div style="background:#fefce8; padding:12px; border-radius:8px; text-align:center; border:1px solid #fef08a;">
                    <div style="font-size:11px; color:#854d0e; font-weight:600; text-transform:uppercase;"><?php echo esc_html(bizmart_text('Last SP', 'Dernier PV', 'آخر سعر بيع')); ?></div>
                    <div id="biz-ph-last-sp" style="font-size:18px; font-weight:700; color:#713f12;">—</div>
                </div>
                <div style="background:#faf5ff; padding:12px; border-radius:8px; text-align:center; border:1px solid #e9d5ff;">
                    <div style="font-size:11px; color:#7e22ce; font-weight:600; text-transform:uppercase;"><?php echo esc_html(bizmart_text('Margin', 'Marge', 'الهامش')); ?></div>
                    <div id="biz-ph-margin" style="font-size:18px; font-weight:700; color:#581c87;">—</div>
                </div>
            </div>

            <!-- Chart -->
            <div style="height:250px; margin-bottom:20px; background:#fafafa; border-radius:8px; padding:8px;">
                <canvas id="biz-ph-chart"></canvas>
            </div>

            <!-- Supplier Comparison -->
            <div id="biz-ph-suppliers" style="margin-bottom:20px; display:none;">
                <h4 style="margin:0 0 8px; font-size:15px; color:#1f2937;">🏭 <?php echo esc_html(bizmart_text('Supplier Comparison', 'Comparaison Fournisseurs', 'مقارنة الموردين')); ?></h4>
                <div id="biz-ph-suppliers-body"></div>
            </div>

            <!-- History Table -->
            <h4 style="margin:0 0 8px; font-size:15px; color:#1f2937;"><?php echo esc_html(bizmart_text('History', 'Historique', 'السجل')); ?></h4>
            <table class="biz-table" style="font-size:13px;">
                <thead>
                    <tr>
                        <th><?php echo esc_html(bizmart_text('Date', 'Date', 'التاريخ')); ?></th>
                        <th><?php echo esc_html(bizmart_text('PP', 'PA', 'شراء')); ?></th>
                        <th><?php echo esc_html(bizmart_text('SP', 'PV', 'بيع')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Margin', 'Marge', 'هامش')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Supplier', 'Fournisseur', 'المورد')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Qty', 'Qté', 'كمية')); ?></th>
                        <th><?php echo esc_html(bizmart_text('Source', 'Source', 'المصدر')); ?></th>
                    </tr>
                </thead>
                <tbody id="biz-ph-tbody"></tbody>
            </table>
            <div id="biz-ph-load-more" style="text-align:center; margin-top:12px; display:none;">
                <button class="biz-btn biz-btn-secondary" onclick="loadMorePriceHistory()" style="padding:6px 16px; font-size:13px;">
                    <?php echo esc_html(bizmart_text('Load More', 'Charger Plus', 'تحميل المزيد')); ?>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
(function(){
    // v3.0 Price History Modal
    var phChart = null;
    var phProductId = 0;
    var phOffset = 0;
    var cfg = window.BizmartDashConfig || {};
    var fmtP = function(v) {
        if (typeof wc_price_format !== 'undefined') return wc_price_format(v);
        var num = parseFloat(v).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2});
        return num + ' ' + (cfg.currency || '');
    };

    window.openPriceHistoryModal = function(productId) {
        phProductId = productId;
        phOffset = 0;
        document.getElementById('biz-ph-tbody').innerHTML = '';
        document.getElementById('biz-price-history-modal').style.display = 'flex';
        document.body.style.overflow = 'hidden';
        loadPriceHistoryData();
        loadPriceChart();
        loadSupplierCompare();
    };

    window.closePriceHistoryModal = function() {
        document.getElementById('biz-price-history-modal').style.display = 'none';
        document.body.style.overflow = '';
        if (phChart) { phChart.destroy(); phChart = null; }
    };

    function loadPriceHistoryData() {
        jQuery.post(cfg.ajax_url, {
            action: 'bizmart_get_product_price_history',
            nonce: cfg.nonce,
            product_id: phProductId,
            limit: 50,
            offset: phOffset
        }, function(res) {
            if (!res.success) return;
            var d = res.data;
            document.getElementById('biz-ph-title').innerHTML = '📊 ' + (d.product_name || 'Price History');
            document.getElementById('biz-ph-wac').textContent = d.wac > 0 ? fmtP(d.wac) : '—';
            document.getElementById('biz-ph-last-pp').textContent = d.last.purchase_price > 0 ? fmtP(d.last.purchase_price) : '—';
            document.getElementById('biz-ph-last-sp').textContent = d.last.selling_price > 0 ? fmtP(d.last.selling_price) : '—';

            var pp = parseFloat(d.last.purchase_price), sp = parseFloat(d.last.selling_price);
            if (sp > 0 && pp > 0) {
                var m = ((sp - pp) / sp * 100).toFixed(1);
                document.getElementById('biz-ph-margin').textContent = m + '%';
                document.getElementById('biz-ph-margin').style.color = m < 10 ? '#dc2626' : '#581c87';
            } else {
                document.getElementById('biz-ph-margin').textContent = '—';
            }

            d.history.forEach(function(h) { appendPriceRow(h); });
            phOffset += d.history.length;
            document.getElementById('biz-ph-load-more').style.display = d.history.length >= 50 ? 'block' : 'none';
        });
    }

    window.loadMorePriceHistory = function() { loadPriceHistoryData(); };

    function appendPriceRow(h) {
        var tr = document.createElement('tr');
        var marginColor = (h.margin_pct !== null && h.margin_pct < 10) ? '#dc2626' : '#059669';
        tr.innerHTML = '<td>' + (h.created_at ? h.created_at.substring(0, 10) : '—') + '</td>'
            + '<td style="font-weight:600;">' + fmtP(h.purchase_price) + '</td>'
            + '<td>' + fmtP(h.selling_price) + '</td>'
            + '<td><span style="color:' + marginColor + '; font-weight:600;">' + (h.margin_pct !== null ? h.margin_pct + '%' : '—') + '</span></td>'
            + '<td>' + (h.supplier_name || '—') + '</td>'
            + '<td>' + (h.quantity || 1) + '</td>'
            + '<td><span style="background:#e5e7eb; padding:2px 6px; border-radius:4px; font-size:11px;">' + (h.source || 'invoice') + '</span></td>';
        document.getElementById('biz-ph-tbody').appendChild(tr);
    }

    function loadPriceChart() {
        jQuery.post(cfg.ajax_url, {
            action: 'bizmart_get_product_price_chart',
            nonce: cfg.nonce,
            product_id: phProductId
        }, function(res) {
            if (!res.success || !res.data.labels.length) return;
            var ctx = document.getElementById('biz-ph-chart').getContext('2d');
            if (phChart) phChart.destroy();
            phChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: res.data.labels,
                    datasets: [
                        { label: '<?php echo esc_js(bizmart_text("Purchase Price", "Prix d\'Achat", "سعر الشراء")); ?>', data: res.data.pp, borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,0.1)', fill: true, tension: 0.3, yAxisID: 'y' },
                        { label: '<?php echo esc_js(bizmart_text("Selling Price", "Prix de Vente", "سعر البيع")); ?>', data: res.data.sp, borderColor: '#10b981', backgroundColor: 'rgba(16,185,129,0.1)', fill: true, tension: 0.3, yAxisID: 'y' },
                        { label: '<?php echo esc_js(bizmart_text("Margin %", "Marge %", "الهامش %")); ?>', data: res.data.margin, borderColor: '#f59e0b', borderDash: [5,5], fill: false, tension: 0.3, yAxisID: 'y1' }
                    ]
                },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    interaction: { mode: 'index', intersect: false },
                    scales: {
                        y: { position: 'left', title: { display: true, text: '<?php echo esc_js(bizmart_text("Price", "Prix", "السعر")); ?>' } },
                        y1: { position: 'right', grid: { drawOnChartArea: false }, title: { display: true, text: '%' }, min: 0 }
                    },
                    plugins: { legend: { position: 'top' } }
                }
            });
        });
    }

    function loadSupplierCompare() {
        jQuery.post(cfg.ajax_url, {
            action: 'bizmart_get_supplier_compare',
            nonce: cfg.nonce,
            product_id: phProductId
        }, function(res) {
            var wrap = document.getElementById('biz-ph-suppliers');
            var body = document.getElementById('biz-ph-suppliers-body');
            if (!res.success || !res.data.length) { wrap.style.display = 'none'; return; }
            wrap.style.display = 'block';
            var html = '<table class="biz-table" style="font-size:13px;"><thead><tr>'
                + '<th><?php echo esc_js(bizmart_text("Supplier", "Fournisseur", "المورد")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Avg Price", "Prix Moyen", "متوسط السعر")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Min", "Min", "أدنى")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Max", "Max", "أقصى")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Orders", "Commandes", "طلبات")); ?></th>'
                + '<th><?php echo esc_js(bizmart_text("Last Order", "Dernière Commande", "آخر طلب")); ?></th>'
                + '</tr></thead><tbody>';
            res.data.forEach(function(s, i) {
                var badge = i === 0 ? ' <span style="background:#dcfce7; color:#166534; padding:2px 6px; border-radius:4px; font-size:10px;">🥇 Best</span>' : '';
                html += '<tr><td style="font-weight:600;">' + s.supplier_name + badge + '</td>'
                    + '<td>' + fmtP(s.avg_price) + '</td>'
                    + '<td>' + fmtP(s.min_price) + '</td>'
                    + '<td>' + fmtP(s.max_price) + '</td>'
                    + '<td>' + s.order_count + '</td>'
                    + '<td>' + (s.last_order ? s.last_order.substring(0, 10) : '—') + '</td></tr>';
            });
            html += '</tbody></table>';
            body.innerHTML = html;
        });
    }

    // Close on backdrop click
    document.getElementById('biz-price-history-modal').addEventListener('click', function(e) {
        if (e.target === this) closePriceHistoryModal();
    });
})();
</script>