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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals, WordPress.DB, WordPress.Security, WordPress.PHP.DevelopmentFunctions

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;
    }
}

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 qty (POS returns store negative qty) ──
        $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;
            }
        }

        // ── Return items: full price refund = full profit loss ──
        // When a customer returns a product, the business gives back the full
        // selling price. The returned stock is tracked by inventory separately.
        // So for profit: the entire negative amount is the loss — no cost offset.
        if ($qty < 0 || $item_total < 0) {
            return ['pp' => 0.0, 'qty' => $qty];
        }

        // ── Detect POS order: if signed_qty meta exists, this is a POS line item ──
        $is_pos_item = ($signed_meta !== '' && $signed_meta !== false);

        // ── Purchase price from order-item snapshot ──
        $snap = wc_get_order_item_meta($item_id, '_purchase_price', true);

        if ($snap !== '' && $snap !== false && is_numeric($snap)) {
            return ['pp' => (float) $snap, 'qty' => $qty];
        }

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

        // ── Non-POS order: fall back to live product meta ──
        $product = $item->get_product();
        if (!$product) {
            return ['pp' => null, 'qty' => $qty];
        }

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

        // Variation fallback: try parent product
        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_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) : '');
    }
}

if (!function_exists('bizmart_dash_price_float')) {
    function bizmart_dash_price_float($value): float {
        return is_numeric($value) ? round((float) $value, 2) : 0.0;
    }
}

if (!function_exists('bizmart_dash_get_selling_price')) {
    function bizmart_dash_get_selling_price($product): float {
        if (!is_object($product) || !method_exists($product, 'get_id')) {
            return 0.0;
        }

        $candidates = [
            method_exists($product, 'get_regular_price') ? $product->get_regular_price() : '',
            method_exists($product, 'get_price') ? $product->get_price() : '',
            get_post_meta((int) $product->get_id(), '_regular_price', true),
            get_post_meta((int) $product->get_id(), '_price', true),
        ];

        foreach ($candidates as $candidate) {
            $value = bizmart_dash_price_float($candidate);
            if ($value > 0) {
                return $value;
            }
        }

        return 0.0;
    }
}

if (!function_exists('bizmart_dash_missing_pricing_state')) {
    function bizmart_dash_missing_pricing_state(float $purchase_price, float $selling_price): array {
        $missing_purchase = $purchase_price <= 0;
        $missing_selling = $selling_price <= 0;

        if ($missing_purchase && $missing_selling) {
            return [
                'missing_purchase' => true,
                'missing_selling' => true,
                'key' => 'both',
                'label' => bizmart_text('Missing both prices', 'Prix achat et vente manquants', 'أسعار الشراء والبيع مفقودة'),
            ];
        }
        if ($missing_purchase) {
            return [
                'missing_purchase' => true,
                'missing_selling' => false,
                'key' => 'purchase',
                'label' => bizmart_text('Missing purchase price', 'Prix d\'achat manquant', 'سعر الشراء مفقود'),
            ];
        }
        if ($missing_selling) {
            return [
                'missing_purchase' => false,
                'missing_selling' => true,
                'key' => 'selling',
                'label' => bizmart_text('Missing selling price', 'Prix de vente manquant', 'سعر البيع مفقود'),
            ];
        }

        return [
            'missing_purchase' => false,
            'missing_selling' => false,
            'key' => 'ready',
            'label' => bizmart_text('Pricing complete', 'Tarification complète', 'التسعير مكتمل'),
        ];
    }
}

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,
            'status'       => ['completed', 'processing', 'on-hold'],
            'type'         => 'shop_order',
            'date_created' => $after . ' 00:00:00...' . $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 [];
        }
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        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
        ));
    }
}

if (!function_exists('bizmart_analytics_margin_pct')) {
    function bizmart_analytics_margin_pct($profit, $sales) {
        return ($sales > 0) ? round(($profit / $sales) * 100, 2) : null;
    }
}

(static function() {

/**
 * 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');



// 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];
    if (defined('WP_DEBUG') && WP_DEBUG) {
        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);
$products_with_missing_pricing = [];
$missing_pricing_count = 0;
// Missing purchase or selling price: get total count + a limited list for the UI.
try {
$missing_cached = get_transient('bizmart_dash_missing_pricing_v3');
if (is_array($missing_cached) && isset($missing_cached['count'], $missing_cached['items']) && is_array($missing_cached['items'])) {
    $missing_pricing_count = (int) $missing_cached['count'];
    $products_with_missing_pricing = $missing_cached['items'];
} else {
    global $wpdb;
    $sql = "
        SELECT p.ID, p.post_type, p.post_parent
        FROM {$wpdb->posts} p
        LEFT JOIN {$wpdb->posts} parent ON (p.post_parent = parent.ID AND p.post_type = 'product_variation')
        LEFT JOIN {$wpdb->postmeta} pm_purchase ON (p.ID = pm_purchase.post_id AND pm_purchase.meta_key = '_purchase_price')
        LEFT JOIN {$wpdb->postmeta} pm_price ON (p.ID = pm_price.post_id AND pm_price.meta_key = '_price')
        WHERE (
            (p.post_type = 'product' AND p.post_status IN ('publish', 'draft', 'private'))
            OR
            (p.post_type = 'product_variation' AND p.post_status = 'inherit' AND parent.post_status IN ('publish', 'draft', 'private'))
        )
        AND (
            pm_purchase.meta_value IS NULL OR pm_purchase.meta_value = '' OR CAST(pm_purchase.meta_value AS DECIMAL(15,4)) <= 0
            OR
            pm_price.meta_value IS NULL OR pm_price.meta_value = '' OR CAST(pm_price.meta_value AS DECIMAL(15,4)) <= 0
        )
    ";

    $results = $wpdb->get_results($sql);

    $grouped_variations = [];
    $simple_missing_ids = [];

    if (!empty($results)) {
        foreach ($results as $row) {
            $id = (int) $row->ID;
            if ($row->post_type === 'product_variation') {
                $parent_id = (int) $row->post_parent;
                if ($parent_id > 0) {
                    $grouped_variations[$parent_id][] = $id;
                }
            } else {
                $simple_missing_ids[] = $id;
            }
        }
    }

    $all_ids_to_process = array_unique(array_merge($simple_missing_ids, array_keys($grouped_variations)));
    $items = [];

    foreach ($all_ids_to_process as $pid) {
        $product = wc_get_product($pid);
        if (!$product) continue;

        $type = $product->get_type();

        if ($type === 'variable') {
            $variation_ids = $grouped_variations[$pid] ?? [];
            if (empty($variation_ids)) {
                $variation_ids = $product->get_children();
            }

            $variation_rows = [];
            foreach ($variation_ids as $vid) {
                $variation_product = wc_get_product($vid);
                if (!$variation_product) continue;

                $variation_purchase = bizmart_dash_price_float(get_post_meta($vid, '_purchase_price', true));
                $variation_selling = bizmart_dash_get_selling_price($variation_product);
                $variation_state = bizmart_dash_missing_pricing_state($variation_purchase, $variation_selling);

                if (!$variation_state['missing_purchase'] && !$variation_state['missing_selling']) {
                    continue;
                }

                $variation_attrs = $variation_product->get_attributes();
                $variation_parts = [];
                foreach ($variation_attrs as $attr_name => $attr_value) {
                    $variation_parts[] = ucwords(str_replace(['pa_', '-'], ['', ' '], $attr_name)) . ': ' . ucfirst(str_replace('-', ' ', $attr_value));
                }

                $variation_rows[] = [
                    'id' => (int) $vid,
                    'name' => !empty($variation_parts) ? implode(' | ', $variation_parts) : ('#' . $vid),
                    'sku' => $variation_product->get_sku(),
                    'purchase_price' => $variation_purchase,
                    'selling_price' => $variation_selling,
                    'status_key' => $variation_state['key'],
                    'status_label' => $variation_state['label'],
                    'missing_purchase' => $variation_state['missing_purchase'],
                    'missing_selling' => $variation_state['missing_selling'],
                ];
            }

            if (empty($variation_rows)) {
                continue;
            }

            $purchase_price = bizmart_dash_price_float(get_post_meta($pid, '_purchase_price', true));
            $selling_price = bizmart_dash_get_selling_price($product);

            $items[] = [
                'id'   => (int) $pid,
                'name' => $product->get_name(),
                'sku'  => $product->get_sku(),
                'link' => admin_url('admin.php?page=bizmart-products&view=create&action=edit&id=' . (int) $pid),
                'type' => $type,
                'variation_ids' => $product->get_children(),
                'variation_rows' => $variation_rows,
                'purchase_price' => $purchase_price,
                'selling_price' => $selling_price,
                'status_key' => 'children',
                'status_label' => bizmart_text('Variations need pricing', 'Des variations ont besoin de prix', 'المتغيرات تحتاج إلى تسعير'),
                'missing_purchase' => true,
                'missing_selling' => false,
                'has_child_issues' => true,
            ];
        } else {
            $purchase_price = bizmart_dash_price_float(get_post_meta($pid, '_purchase_price', true));
            $selling_price = bizmart_dash_get_selling_price($product);
            $pricing_state = bizmart_dash_missing_pricing_state($purchase_price, $selling_price);

            if (!$pricing_state['missing_purchase'] && !$pricing_state['missing_selling']) {
                continue;
            }

            $items[] = [
                'id'   => (int) $pid,
                'name' => $product->get_name(),
                'sku'  => $product->get_sku(),
                'link' => admin_url('admin.php?page=bizmart-products&view=create&action=edit&id=' . (int) $pid),
                'type' => $type,
                'variation_ids' => [],
                'variation_rows' => [],
                'purchase_price' => $purchase_price,
                'selling_price' => $selling_price,
                'status_key' => $pricing_state['key'],
                'status_label' => $pricing_state['label'],
                'missing_purchase' => $pricing_state['missing_purchase'],
                'missing_selling' => $pricing_state['missing_selling'],
                'has_child_issues' => false,
            ];
        }
    }

    $missing_pricing_count = count($items);
    $products_with_missing_pricing = array_slice($items, 0, 50);

    set_transient('bizmart_dash_missing_pricing_v3', [
        'count' => $missing_pricing_count,
        'items' => $products_with_missing_pricing,
    ], $dash_cache_ttl);
}
} catch (\Throwable $e) {
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('[Bizmart Dashboard] Missing prices query error: ' . $e->getMessage());
    }
}

$products_without_price = $products_with_missing_pricing;
$missing_purchase_price_count = $missing_pricing_count;

// 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', 'week', 'month', 'year', '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;
$installed_at_option = (string) get_option('bizmart_core_installed_at', '');
$installed_start_date = preg_match('/^\d{4}-\d{2}-\d{2}/', $installed_at_option) ? substr($installed_at_option, 0, 10) : $first_order_date;

// Period start dates — defined early so chart range + metric cards both use them
$today_str       = wp_date('Y-m-d');
$week_start_dt   = new DateTimeImmutable($today_str);
$configured_week_start = (int) get_option('start_of_week', 0);
for ($week_guard = 0; $week_guard < 7 && (int) $week_start_dt->format('w') !== $configured_week_start; $week_guard++) {
    $week_start_dt = $week_start_dt->modify('-1 day');
}
$week_start_str  = $week_start_dt->format('Y-m-d');
$week_end_str    = $week_start_dt->modify('+6 days')->format('Y-m-d');
$month_start_str = wp_date('Y-m-01');
$month_end_str   = wp_date('Y-m-t');
$year_start_str  = wp_date('Y-01-01');
$year_end_str    = wp_date('Y-12-31');

if ($bizmart_wc_active) {
    $first = wc_get_orders([
        'limit'  => 1,
        'orderby'=> 'date_created',
        'order'  => 'ASC',
        'type'   => 'shop_order',
        'status' => function_exists('bizmart_analytics_reporting_statuses') ? bizmart_analytics_reporting_statuses() : ['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
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $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 ($installed_start_date === '' || strtotime($installed_start_date) === false || strtotime($installed_start_date) > strtotime($today_str)) {
    $installed_start_date = $first_data_date;
}

$range_tooltips = [
    'week' => sprintf(
        '%s %s → %s',
        bizmart_text('This week', 'Cette semaine', 'هذا الأسبوع'),
        date_i18n('d M Y', strtotime($week_start_str)),
        date_i18n('d M Y', strtotime($week_end_str))
    ),
    'month' => sprintf(
        '%s %s → %s',
        bizmart_text('This month', 'Ce mois', 'هذا الشهر'),
        date_i18n('d M Y', strtotime($month_start_str)),
        date_i18n('d M Y', strtotime($month_end_str))
    ),
    'year' => sprintf(
        '%s %s → %s',
        bizmart_text('This year', 'Cette année', 'هذه السنة'),
        date_i18n('d M Y', strtotime($year_start_str)),
        date_i18n('d M Y', strtotime($year_end_str))
    ),
    'all' => sprintf(
        '%s %s · %s %s',
        bizmart_text('Installed on', 'Installé le', 'تم التثبيت في'),
        date_i18n('d M Y', strtotime($installed_start_date)),
        bizmart_text('Data shown through', 'Données affichées jusqu’au', 'البيانات معروضة حتى'),
        date_i18n('d M Y', strtotime($today_str))
    ),
];

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 {
    switch ($range) {
        case 'week':  $start_date = $week_start_str;  break;
        case 'month': $start_date = $month_start_str; break;
        case 'year':  $start_date = $year_start_str;  break;
        case '30':    $start_date = wp_date('Y-m-d', strtotime('-29 days')); break;
        case 'all':   $start_date = $first_data_date;  break;
        default:      $start_date = wp_date('Y-m-d', strtotime('-6 days')); break; // '7'
    }
}



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

try {
    $orders_range    = bizmart_analytics_get_orders_range($start_date, $end_date);
    $orders_metrics  = bizmart_analytics_get_orders_range($first_data_date, $today_str);
    $expenses_range  = bizmart_analytics_get_expenses_range($start_date, $end_date);
    $expenses_metrics = bizmart_analytics_get_expenses_range($first_data_date, $today_str);
} catch (\Throwable $e) {
    $dashboard_data_error = true;
    if (defined('WP_DEBUG') && WP_DEBUG) {
        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  = [];

/**
 * Process ALL orders for metric cards (independent of selected date filter).
 */
try {
foreach ($orders_metrics as $order) {
    if ($order instanceof WC_Order_Refund) continue;

    $date = $order->get_date_created() ? $order->get_date_created()->date('Y-m-d') : $today_str;

    // Discounts — get_total_discount() already includes item-level discounts
    $discount = (float)$order->get_total_discount();

    $line_sales = 0.0;
    $profit     = 0.0;
    foreach ($order->get_items() as $item) {
        $item_total = (float)$item->get_total();
        $line_sales += $item_total;

        $resolved = bizmart_analytics_resolve_item_cost($item, $purchase_price_cache);
        $pp  = $resolved['pp'];
        $qty = $resolved['qty'];

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

    $metrics['all']['sales']     += $line_sales;
    $metrics['all']['profit']    += $profit;
    $metrics['all']['orders']    += 1;
    $metrics['all']['discounts'] += $discount;

    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']     += $line_sales;
            $metrics[$key]['profit']    += $profit;
            $metrics[$key]['orders']    += 1;
            $metrics[$key]['discounts'] += $discount;
        }
    }
}

// Process expenses for metric cards (full history)
foreach ($expenses_metrics as $expense) {
    $date   = $expense->expense_date;
    $amount = (float)$expense->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;
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('[Bizmart Dashboard] Metrics processing error: ' . $e->getMessage());
    }
}

/**
 * Process filtered orders for chart, top products, and recent orders.
 */
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;

    // Sales: sum of line item totals (excludes shipping/tax/fees for accurate margin)
    $line_sales = 0.0;

    // Profit: sum of line totals minus (qty * purchase price)
    $profit = 0.0;
    foreach ($order->get_items() as $item) {
        $product    = $item->get_product();
        $item_total = (float)$item->get_total();
        $line_sales += $item_total;

        $resolved    = bizmart_analytics_resolve_item_cost($item, $purchase_price_cache);
        $pp          = $resolved['pp'];
        $qty         = $resolved['qty'];
        $pid         = $product ? $product->get_id() : 0;

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

        if ($pid && $product) {
            if (!isset($products_agg[$pid])) {
                $products_agg[$pid] = [
                    'id'             => $pid,
                    'name'           => $product->get_name(),
                    'qty'            => 0,
                    'sales'          => 0.0,
                    'profit'         => 0.0,
                    'link'           => admin_url('admin.php?page=bizmart-products&view=create&action=edit&id=' . (int) $pid),
                    'purchase_price' => $pp
                ];
            }
            $products_agg[$pid]['qty']    += $qty;
            $products_agg[$pid]['sales']  += $item_total;
            $products_agg[$pid]['profit'] += $line_profit;
        }
    }

    // Use line-item sales for consistent margin calculation
    $total = $line_sales;

    // 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'   => admin_url('admin.php?page=bizmart-orders&order_id=' . (int) $order_id),
        'date'   => $date
    ];
}

// Process expenses for filtered chart only
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;
    }
}
} catch (\Throwable $e) {
    $dashboard_data_error = true;
    if (defined('WP_DEBUG') && WP_DEBUG) {
        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;

                foreach ($order->get_items() as $item) {
                    $item_total = (float) $item->get_total();
                    $prev_sales += $item_total;

                    $resolved = bizmart_analytics_resolve_item_cost($item, $purchase_price_cache);
                    $pp  = $resolved['pp'];
                    $qty = $resolved['qty'];

                    $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', '') : '');


?>
<?php
// Chart.js is enqueued centrally via admin_enqueue_scripts hook in bizmart-cost-of-goods.php

// 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 !important; margin: 0 auto; text-shadow: none;">📊 <?php echo esc_html(bizmart_text('Dashboard', 'Tableau de bord', 'لوحة التحكم')); ?> — <span style="font-weight:400; color:#ffffff !important;"><?php echo defined('BIZMART_ADDON_VERSION') ? 'Bizmart Premium' : 'Bizmart Free'; ?></span></h1>
            <p style="margin: 8px auto 0; color:#ffffff !important; opacity:0.9;"><?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 style="margin-top: 15px;">
                <a href="<?php echo esc_url(bizmart_get_option('biz_youtube_video_url', 'https://www.youtube.com/watch?v=dNjr_kZAVSU')); ?>" target="_blank" rel="noopener noreferrer" class="biz-btn" style="background: #ef4444; color: #ffffff !important; display: inline-flex; align-items: center; gap: 8px; text-decoration: none; border-radius: 999px; padding: 10px 24px; font-weight: 700; font-size: 14px; box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4); border: 2px solid #ffffff; transition: all 0.3s ease;">
                    <i class="fab fa-youtube" style="font-size: 18px;"></i>
                    <span><?php echo esc_html(bizmart_text('Watch Now', 'Regarder maintenant', 'شاهد الآن')); ?></span>
                </a>
            </div>
        </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);
                    }
                ?>
                <?php $is_custom_range = !empty($start_date_param) && !empty($end_date_param); ?>
                <div class="biz-chip-row" style="display:flex; gap:8px; flex-wrap:wrap; justify-content:flex-start; margin-top:-2px;">
                    <a class="biz-chip<?php echo (!$is_custom_range && $range === '7') ? ' active' : ''; ?>" 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<?php echo (!$is_custom_range && $range === 'week') ? ' active' : ''; ?>" href="<?php echo esc_url(add_query_arg('range','week', $chip_base)); ?>"><?php echo esc_html(bizmart_text('This week', 'Cette semaine', 'هذا الأسبوع')); ?></a>
                    <a class="biz-chip<?php echo (!$is_custom_range && $range === '30') ? ' active' : ''; ?>" 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<?php echo (!$is_custom_range && $range === 'month') ? ' active' : ''; ?>" href="<?php echo esc_url(add_query_arg('range','month', $chip_base)); ?>"><?php echo esc_html(bizmart_text('This month', 'Ce mois', 'هذا الشهر')); ?></a>
                    <a class="biz-chip<?php echo (!$is_custom_range && $range === 'year') ? ' active' : ''; ?>" href="<?php echo esc_url(add_query_arg('range','year', $chip_base)); ?>"><?php echo esc_html(bizmart_text('This year', 'Cette année', 'هذه السنة')); ?></a>
                    <a class="biz-chip<?php echo (!$is_custom_range && $range === 'all') ? ' active' : ''; ?>" 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 wp_kses_post(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 wp_kses_post(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 wp_kses_post(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 wp_kses_post(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; ?>

        <?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) : [];

        // Stock Alerts calculation with caching
        $stock_alerts_cached = get_transient('bizmart_dash_stock_alerts_v1');
        if (is_array($stock_alerts_cached)) {
            $crisis_count = (int) $stock_alerts_cached['crisis'];
            $low_stock_count = (int) $stock_alerts_cached['low'];
        } else {
            $crisis_count = 0;
            $low_stock_count = 0;
            if ($bizmart_wc_active) {
                $all_items = wc_get_products(array(
                    'status' => array('publish', 'draft', 'private'),
                    'type' => array('simple', 'variation'),
                    'limit' => 2000,
                    'stock_status' => array('instock', 'outofstock', 'onbackorder'),
                    'paginate' => false,
                ));
                $low_stock_threshold = 5;
                foreach ($all_items as $item) {
                    if (!$item || !$item->managing_stock()) continue;
                    $post_status = get_post_status($item->get_id());
                    if ($post_status === 'auto-draft') continue;
                    if (strpos(strtoupper($item->get_name()), 'AUTO-DRAFT') !== false) continue;
                    
                    $qty = $item->get_stock_quantity();
                    $status = $item->get_stock_status();
                    
                    if ($qty === 0 || $status === 'outofstock') {
                        $crisis_count++;
                    } elseif ($qty !== null && $qty > 0 && $qty <= $low_stock_threshold) {
                        $low_stock_count++;
                    }
                }
            }
            set_transient('bizmart_dash_stock_alerts_v1', [
                'crisis' => $crisis_count,
                'low' => $low_stock_count,
            ], $dash_cache_ttl);
        }

        // Pending orders calculation
        $pending_orders_count = 0;
        if ($bizmart_wc_active) {
            foreach (['pending', 'on-hold', 'failed'] as $st) {
                $pending_orders_count += count(wc_get_orders(['status' => $st, 'limit' => -1, 'return' => 'ids']));
            }
        }

        $has_dashboard_alert_ctas = !empty($low_margin_products) || $missing_pricing_count > 0 || $crisis_count > 0 || $low_stock_count > 0 || $pending_orders_count > 0;
        ?>
        <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 wp_kses_post(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 wp_kses_post(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" style="width:100%;">
                    <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_pricing_count > 0): ?>
                    <div style="border-top:1px solid rgba(255,255,255,0.3); margin:8px 0 6px; padding-top:8px;">
                        <span onclick="openMissingPricesPopup()" style="display:inline-flex; align-items:center; gap:4px; background:rgba(239,68,68,0.85); color:#fff; border-radius:999px; padding:3px 10px; font-size:12px; font-weight:700; cursor:pointer;" title="<?php echo esc_attr(bizmart_text('Click to view missing prices', 'Cliquer pour voir les prix manquants', 'انقر لعرض الأسعار الناقصة')); ?>">
                            ⚠ <?php echo intval($missing_pricing_count); ?> <?php echo esc_html(bizmart_text('missing', 'manquants', 'ناقص')); ?>
                        </span>
                    </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 wp_kses_post(bizmart_dash_money($stock_value)); ?></strong></div>
                    <div><?php echo esc_html(bizmart_text('Achat:', 'Achat :', 'الشراء:')); ?> <strong><?php echo wp_kses_post(bizmart_dash_money($stock_purchase_value)); ?></strong></div>
                </div>
            </div>
        </div>

        <?php if ($has_dashboard_alert_ctas): ?>
        <div id="biz-stock-alert-hub" style="display:flex; flex-wrap:wrap; gap:10px; align-items:center; margin:16px 0 24px; padding:0; background:none; border:none; box-shadow:none;">
            <div style="font-size:13px; font-weight:700; color:#475569; margin-right:4px; text-transform:uppercase; letter-spacing:0.05em;">
                <?php echo esc_html(bizmart_text('Attention Center', 'Centre d\'attention', 'مركز التنبيهات')); ?>
            </div>
            <?php if (!empty($low_margin_products)): ?>
            <button type="button" id="biz-low-margin-cta" onclick="openLowMarginPopup()" style="display:inline-flex; align-items:center; gap:8px; background:linear-gradient(135deg,#fee2e2,#fecaca); color:#991b1b; border:1px solid #f87171; border-radius:999px; padding:8px 14px; font-size:13px; font-weight:700; cursor:pointer; box-shadow:0 8px 18px rgba(239,68,68,0.10);">
                <span>⚠️</span>
                <span><?php echo esc_html(bizmart_text('Low Margin', 'Marge Faible', 'هامش منخفض')); ?></span>
                <span id="biz-low-margin-cta-count" style="background:rgba(153,27,27,0.12); border-radius:999px; padding:2px 8px; font-size:12px;"><?php echo intval(count($low_margin_products)); ?></span>
                <span data-low-margin-threshold-label style="font-size:12px; font-weight:600; opacity:0.85;"><?php echo esc_html(bizmart_text('below', 'sous', 'أقل من')); ?> <?php echo esc_html($margin_threshold); ?>%</span>
            </button>
            <?php endif; ?>
            <?php if ($missing_pricing_count > 0): ?>
            <button type="button" id="biz-missing-pricing-cta" onclick="openMissingPricesPopup()" style="display:inline-flex; align-items:center; gap:8px; background:linear-gradient(135deg,#dbeafe,#bfdbfe); color:#1d4ed8; border:1px solid #60a5fa; border-radius:999px; padding:8px 14px; font-size:13px; font-weight:700; cursor:pointer; box-shadow:0 8px 18px rgba(59,130,246,0.10);">
                <span>🧾</span>
                <span><?php echo esc_html(bizmart_text('Missing Prices', 'Prix Manquants', 'الأسعار الناقصة')); ?></span>
                <span id="biz-missing-pricing-cta-count" style="background:rgba(29,78,216,0.12); border-radius:999px; padding:2px 8px; font-size:12px;"><?php echo intval($missing_pricing_count); ?></span>
            </button>
            <?php endif; ?>
            <?php if ($crisis_count > 0): ?>
            <button type="button" id="biz-crisis-stock-cta" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=bizmart-products&view=alerts')); ?>'" style="display:inline-flex; align-items:center; gap:8px; background:linear-gradient(135deg,#ffe4e6,#fecdd3); color:#9f1239; border:1px solid #fda4af; border-radius:999px; padding:8px 14px; font-size:13px; font-weight:700; cursor:pointer; box-shadow:0 8px 18px rgba(225,29,72,0.10);">
                <span>🚨</span>
                <span><?php echo esc_html(bizmart_text('Out of Stock', 'Rupture de Stock', 'نفاد المخزون')); ?></span>
                <span id="biz-crisis-stock-cta-count" style="background:rgba(159,18,57,0.12); border-radius:999px; padding:2px 8px; font-size:12px;"><?php echo intval($crisis_count); ?></span>
            </button>
            <?php endif; ?>
            <?php if ($low_stock_count > 0): ?>
            <button type="button" id="biz-low-stock-cta" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=bizmart-products&view=alerts')); ?>'" style="display:inline-flex; align-items:center; gap:8px; background:linear-gradient(135deg,#fef3c7,#fde68a); color:#92400e; border:1px solid #fcd34d; border-radius:999px; padding:8px 14px; font-size:13px; font-weight:700; cursor:pointer; box-shadow:0 8px 18px rgba(217,119,6,0.10);">
                <span>⚠️</span>
                <span><?php echo esc_html(bizmart_text('Low Stock', 'Stock Faible', 'مخزون منخفض')); ?></span>
                <span id="biz-low-stock-cta-count" style="background:rgba(146,64,14,0.12); border-radius:999px; padding:2px 8px; font-size:12px;"><?php echo intval($low_stock_count); ?></span>
            </button>
            <?php endif; ?>
            <?php if ($pending_orders_count > 0): ?>
            <button type="button" id="biz-pending-orders-cta" onclick="window.location.href='<?php echo esc_url(admin_url('admin.php?page=bizmart-orders&status=pending')); ?>'" style="display:inline-flex; align-items:center; gap:8px; background:linear-gradient(135deg,#e0e7ff,#c7d2fe); color:#3730a3; border:1px solid #a5b4fc; border-radius:999px; padding:8px 14px; font-size:13px; font-weight:700; cursor:pointer; box-shadow:0 8px 18px rgba(79,70,229,0.10);">
                <span>📦</span>
                <span><?php echo esc_html(bizmart_text('Pending Orders', 'Commandes en attente', 'الطلبات المعلقة')); ?></span>
                <span id="biz-pending-orders-cta-count" style="background:rgba(55,48,163,0.12); border-radius:999px; padding:2px 8px; font-size:12px;"><?php echo intval($pending_orders_count); ?></span>
            </button>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- Period metrics with enhanced cards -->
        <!-- Period metrics with enhanced cards -->
        <div class="biz-row">
            <div class="biz-card" data-range-tooltip="<?php echo esc_attr($range_tooltips['week']); ?>">
                <div class="biz-label"><?php echo esc_html(bizmart_text('This week', 'Cette semaine', 'هذا الأسبوع')); ?></div>
                <div class="biz-value"><?php echo wp_kses_post(bizmart_dash_money($metrics['week']['sales'])); ?></div>
                <?php
                $week_sales = (float)$metrics['week']['sales'];
                $week_profit = (float)$metrics['week']['profit'];
                $week_orders = (int)$metrics['week']['orders'];
                $week_margin = ($week_sales > 0) ? round(($week_profit / $week_sales) * 100, 1) : 0;
                $week_aov = ($week_orders > 0) ? ($week_sales / $week_orders) : 0;
                ?>
                <div class="biz-small"><?php echo esc_html(bizmart_text('Profit:', 'Profit :', 'الربح:')); ?> <?php echo wp_kses_post(bizmart_dash_money($metrics['week']['profit'])); ?> (<?php echo $week_margin; ?>%) | <?php echo esc_html(bizmart_text('Orders:', 'Commandes :', 'الطلبات:')); ?> <?php echo intval($week_orders); ?></div>
            </div>
            <div class="biz-card" data-range-tooltip="<?php echo esc_attr($range_tooltips['month']); ?>">
                <div class="biz-label"><?php echo esc_html(bizmart_text('This month', 'Ce mois', 'هذا الشهر')); ?></div>
                <div class="biz-value"><?php echo wp_kses_post(bizmart_dash_money($metrics['month']['sales'])); ?></div>
                <?php
                $month_sales = (float)$metrics['month']['sales'];
                $month_profit = (float)$metrics['month']['profit'];
                $month_orders = (int)$metrics['month']['orders'];
                $month_margin = ($month_sales > 0) ? round(($month_profit / $month_sales) * 100, 1) : 0;
                $month_aov = ($month_orders > 0) ? ($month_sales / $month_orders) : 0;
                ?>
                <div class="biz-small"><?php echo esc_html(bizmart_text('Profit:', 'Profit :', 'الربح:')); ?> <?php echo wp_kses_post(bizmart_dash_money($metrics['month']['profit'])); ?> (<?php echo $month_margin; ?>%) | <?php echo esc_html(bizmart_text('Orders:', 'Commandes :', 'الطلبات:')); ?> <?php echo intval($month_orders); ?></div>
            </div>
            <div class="biz-card" data-range-tooltip="<?php echo esc_attr($range_tooltips['year']); ?>">
                <div class="biz-label"><?php echo esc_html(bizmart_text('This year', 'Cette année', 'هذه السنة')); ?></div>
                <div class="biz-value"><?php echo wp_kses_post(bizmart_dash_money($metrics['year']['sales'])); ?></div>
                <?php
                $year_sales = (float)$metrics['year']['sales'];
                $year_profit = (float)$metrics['year']['profit'];
                $year_orders = (int)$metrics['year']['orders'];
                $year_margin = ($year_sales > 0) ? round(($year_profit / $year_sales) * 100, 1) : 0;
                $year_aov = ($year_orders > 0) ? ($year_sales / $year_orders) : 0;
                ?>
                <div class="biz-small"><?php echo esc_html(bizmart_text('Profit:', 'Profit :', 'الربح:')); ?> <?php echo wp_kses_post(bizmart_dash_money($metrics['year']['profit'])); ?> (<?php echo $year_margin; ?>%) | <?php echo esc_html(bizmart_text('Orders:', 'Commandes :', 'الطلبات:')); ?> <?php echo intval($year_orders); ?></div>
            </div>
            <div class="biz-card" data-range-tooltip="<?php echo esc_attr($range_tooltips['all']); ?>">
                <div class="biz-label"><?php echo esc_html(bizmart_text('Since the beginning', 'Depuis le début', 'منذ البداية')); ?></div>
                <div class="biz-value"><?php echo wp_kses_post(bizmart_dash_money($metrics['all']['sales'])); ?></div>
                <?php
                $all_sales = (float)$metrics['all']['sales'];
                $all_profit = (float)$metrics['all']['profit'];
                $all_orders = (int)$metrics['all']['orders'];
                $all_margin = ($all_sales > 0) ? round(($all_profit / $all_sales) * 100, 1) : 0;
                $all_aov = ($all_orders > 0) ? ($all_sales / $all_orders) : 0;
                ?>
                <div class="biz-small"><?php echo esc_html(bizmart_text('Profit:', 'Profit :', 'الربح:')); ?> <?php echo wp_kses_post(bizmart_dash_money($metrics['all']['profit'])); ?> (<?php echo $all_margin; ?>%) | <?php echo esc_html(bizmart_text('Orders:', 'Commandes :', 'الطلبات:')); ?> <?php echo intval($all_orders); ?></div>
            </div>
        </div>

        <!-- Row 1: Chart & Recent Orders -->
        <div class="biz-dash-layout-grid-two">
            <!-- Chart Panel -->
            <div class="biz-panel" style="margin: 0;">
                <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 {
                                $range_labels = [
                                    '7'     => bizmart_text('Last 7 days', '7 derniers jours', 'آخر 7 أيام'),
                                    'week'  => bizmart_text('This week', 'Cette semaine', 'هذا الأسبوع'),
                                    '30'    => bizmart_text('Last 30 days', '30 derniers jours', 'آخر 30 يومًا'),
                                    'month' => bizmart_text('This month', 'Ce mois', 'هذا الشهر'),
                                    'year'  => bizmart_text('This year', 'Cette année', 'هذه السنة'),
                                    'all'   => bizmart_text('Since the beginning', 'Depuis le début', 'منذ البداية'),
                                ];
                                echo esc_html($range_labels[$range] ?? $range_labels['7']);
                            }
                        ?>
                    </p>
                </div>
                <div style="height:350px; margin-top:12px;">
                    <canvas id="bizChart"></canvas>
                </div>
            </div>

            <!-- Recent Orders -->
            <div class="biz-panel" style="margin: 0; display: flex; flex-direction: column;">
                <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="flex: 1; padding-right:8px; scroll-behavior: smooth; max-height: 350px; overflow-y: auto;">
                    <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 wp_kses_post(bizmart_dash_money($o['total'])); ?></td>
                                    <td><?php echo wp_kses_post(bizmart_dash_money($o['profit'])); ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Row 2: Top Products & Most Profitable -->
        <div class="biz-dash-layout-grid-half">
            <!-- Top Products -->
            <div id="biz-top-products-panel" class="biz-panel" style="margin: 0;">
                <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; max-height: 350px; overflow-y: auto;">
                    <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 wp_kses_post(bizmart_dash_money($p['sales'])); ?></td>
                                    <td><?php echo wp_kses_post(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" style="margin: 0;">
                <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', 'Products générant le plus de marge bénéficiaire', 'المنتجات التي تحقق أعلى ربح')); ?></p>
                </div>
                <div id="biz-top-profit-scroll" class="biz-scroll" style="padding-right:8px; scroll-behavior: smooth; max-height: 350px; overflow-y: auto;">
                    <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 wp_kses_post(bizmart_dash_money($p['sales'])); ?></td>
                                    <td><?php echo wp_kses_post(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>
        </div>

    </div>
</div>

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

<?php if (!empty($low_margin_products)): ?>
<div id="biz-low-margin-popup" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.62); z-index:99999; align-items:center; justify-content:center; padding:20px; backdrop-filter:blur(4px);">
    <div style="background:#fff; border-radius:18px; max-width:1080px; 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:22px 24px; border-bottom:1px solid #e5e7eb; background:linear-gradient(135deg,#fee2e2,#fecaca); color:#991b1b; display:flex; justify-content:space-between; align-items:center; gap:16px;">
            <div>
                <h2 style="margin:0; font-size:20px; font-weight:800;"><?php echo esc_html(bizmart_text('Low Margin Products', 'Produits à Faible Marge', 'منتجات بهامش منخفض')); ?></h2>
                <p style="margin:6px 0 0; font-size:13px; opacity:0.9;"><?php echo esc_html(bizmart_text('Adjust purchase price, selling price, or target margin directly from the dashboard.', 'Ajustez le prix d\'achat, le prix de vente ou la marge cible directement depuis le tableau de bord.', 'عدّل سعر الشراء أو سعر البيع أو الهامش المستهدف مباشرة من لوحة التحكم.')); ?></p>
            </div>
            <button type="button" onclick="closeLowMarginPopup()" style="background:rgba(153,27,27,0.08); border:1px solid rgba(153,27,27,0.2); color:#991b1b; width:38px; height:38px; border-radius:10px; font-size:20px; cursor:pointer;">&times;</button>
        </div>
        <div style="padding:18px 24px; border-bottom:1px solid #e5e7eb; background:#fff7f7; display:flex; gap:12px; align-items:end; flex-wrap:wrap;">
            <div>
                <div style="font-size:12px; font-weight:700; color:#64748b; text-transform:uppercase; letter-spacing:0.05em;"><?php echo esc_html(bizmart_text('Default low margin threshold', 'Seuil de marge faible par défaut', 'الحد الافتراضي للهامش المنخفض')); ?></div>
                <div style="display:flex; align-items:center; gap:8px; margin-top:6px;">
                    <input type="number" id="biz-low-margin-threshold" value="<?php echo esc_attr($margin_threshold); ?>" min="0" max="100" step="0.1" style="width:110px; padding:10px 12px; border:1px solid #d1d5db; border-radius:10px; font-size:14px; font-weight:700;">
                    <span style="font-weight:700; color:#475569;">%</span>
                </div>
            </div>
            <button type="button" id="biz-save-low-margin-threshold" class="biz-btn biz-btn-secondary" style="height:42px;"><?php echo esc_html(bizmart_text('Save default', 'Enregistrer le défaut', 'حفظ الافتراضي')); ?></button>
            <div id="biz-low-margin-threshold-status" style="font-size:13px; color:#64748b;"></div>
        </div>
        <div style="padding:20px 24px; overflow:auto; flex:1;">
            <table class="biz-table" style="width:100%;">
                <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>
                        <th><?php echo esc_html(bizmart_text('Action', 'Action', 'الإجراء')); ?></th>
                    </tr>
                </thead>
                <tbody id="biz-low-margin-tbody">
                    <?php foreach ($low_margin_products as $lm): ?>
                    <tr data-low-margin-row data-product-id="<?php echo intval($lm['product_id']); ?>">
                        <td>
                            <a href="#" onclick="openPriceHistoryModal(<?php echo intval($lm['product_id']); ?>); return false;" style="color:#4f46e5; text-decoration:none; font-weight:600;">
                                <?php echo esc_html($lm['name']); ?>
                            </a>
                        </td>
                        <td>
                            <input type="number" min="0" step="0.01" value="<?php echo esc_attr($lm['purchase_price']); ?>" data-role="purchase" style="width:120px; padding:8px 10px; border:1px solid #d1d5db; border-radius:8px;">
                        </td>
                        <td>
                            <input type="number" min="0.01" step="0.01" value="<?php echo esc_attr($lm['selling_price']); ?>" data-role="selling" style="width:120px; padding:8px 10px; border:1px solid #d1d5db; border-radius:8px;">
                        </td>
                        <td>
                            <div style="display:flex; align-items:center; gap:6px;">
                                <input type="number" min="0" max="99.99" step="0.01" value="<?php echo esc_attr($lm['margin_pct']); ?>" data-role="margin" style="width:96px; padding:8px 10px; border:1px solid #d1d5db; border-radius:8px;">
                                <span style="font-weight:700; color:#64748b;">%</span>
                            </div>
                        </td>
                        <td data-role="last-change" style="font-size:13px; color:#6b7280;"><?php echo esc_html($lm['last_change'] ? date_i18n('d M Y', strtotime($lm['last_change'])) : '—'); ?></td>
                        <td>
                            <button type="button" data-action="save-low-margin-row" class="biz-btn biz-btn-primary" style="white-space:nowrap;"><?php echo esc_html(bizmart_text('Save', 'Enregistrer', 'حفظ')); ?></button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div id="biz-low-margin-empty" style="display:none; text-align:center; padding:36px 12px; color:#64748b; font-weight:600;">
                <?php echo esc_html(bizmart_text('No low margin products remain in this list.', 'Aucun produit à faible marge ne reste dans cette liste.', 'لم تعد هناك منتجات منخفضة الهامش في هذه القائمة.')); ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- 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:#fff; border-radius:18px; max-width:1120px; 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:22px 24px; border-bottom:1px solid #e5e7eb; background:linear-gradient(135deg,#dbeafe,#bfdbfe); color:#1d4ed8; display:flex; justify-content:space-between; align-items:center; gap:16px;">
            <div>
                <h2 style="margin:0; font-size:20px; font-weight:800;"><?php echo esc_html(bizmart_text('Missing Pricing', 'Tarification Incomplète', 'تسعير غير مكتمل')); ?></h2>
                <p style="margin:6px 0 0; font-size:13px; opacity:0.9;"><?php echo esc_html(bizmart_text('Set purchase price, selling price, or margin target from one table. Products leave this list once pricing is complete.', 'Définissez le prix d\'achat, le prix de vente ou la marge cible depuis un seul tableau. Les produits quittent cette liste une fois la tarification complète.', 'حدّد سعر الشراء أو سعر البيع أو نسبة الهامش من جدول واحد. يخرج المنتج من هذه القائمة فور اكتمال التسعير.')); ?></p>
            </div>
            <button type="button" onclick="closeMissingPricesPopup()" style="background:rgba(29,78,216,0.08); border:1px solid rgba(29,78,216,0.18); color:#1d4ed8; width:38px; height:38px; border-radius:10px; font-size:20px; cursor:pointer;">&times;</button>
        </div>
        <div style="padding:20px 24px; overflow-y:auto; flex:1; background:#f8fbff;">
            <table class="biz-table" style="width:100%;">
                <thead>
                    <tr>
                        <th style="width:28%;"><?php echo esc_html(bizmart_text('Product', 'Produit', 'المنتج')); ?></th>
                        <th style="width:14%;"><?php echo esc_html(bizmart_text('Status', 'Statut', 'الحالة')); ?></th>
                        <th style="width:10%;"><?php echo esc_html(bizmart_text('SKU', 'SKU', 'رمز المنتج')); ?></th>
                        <th style="width:14%;"><?php echo esc_html(bizmart_text('Purchase Price', "Prix d'Achat", 'سعر الشراء')); ?></th>
                        <th style="width:14%;"><?php echo esc_html(bizmart_text('Selling Price', 'Prix de Vente', 'سعر البيع')); ?></th>
                        <th style="width:10%;"><?php echo esc_html(bizmart_text('Margin %', 'Marge %', 'الهامش %')); ?></th>
                        <th style="width:10%;"><?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_rows = $ppp['variation_rows'] ?? [];
                        $row_purchase = (float) ($ppp['purchase_price'] ?? 0);
                        $row_selling = (float) ($ppp['selling_price'] ?? 0);
                        $row_margin = $row_selling > 0 ? round((($row_selling - $row_purchase) / $row_selling) * 100, 2) : 0;
                    ?>
                    <tr id="biz-missing-row-<?php echo intval($ppp['id']); ?>" data-missing-pricing-row data-row-kind="<?php echo esc_attr($is_variable ? 'group' : 'product'); ?>" data-product-id="<?php echo intval($ppp['id']); ?>" data-group-id="<?php echo intval($ppp['id']); ?>" data-countable="1" data-has-child-issues="<?php echo !empty($var_rows) ? '1' : '0'; ?>" style="background:#fff;">
                        <td>
                            <div style="font-weight:600; color:#111827;">
                                <a href="#" onclick="openProductPopup(<?php echo intval($ppp['id']); ?>); return false;" style="color:#1f2937; text-decoration:none; font-weight:700;">
                                    <?php echo esc_html($ppp['name']); ?>
                                </a>
                                <?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_rows)): ?>
                            <div style="margin-top:4px; font-size:12px; color:#6b7280;">
                                <?php echo count($var_rows); ?> <?php echo esc_html(bizmart_text('variations need pricing', 'variations à corriger', 'متغيرات تحتاج تسعير')); ?>
                                — <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>
                            <span data-role="status-badge" data-status-key="<?php echo esc_attr($ppp['status_key']); ?>" style="display:inline-flex; align-items:center; gap:6px; background:<?php echo esc_attr($ppp['status_key'] === 'both' ? '#fee2e2' : ($ppp['status_key'] === 'selling' ? '#dbeafe' : ($ppp['status_key'] === 'children' ? '#ede9fe' : '#fef3c7'))); ?>; color:<?php echo esc_attr($ppp['status_key'] === 'both' ? '#991b1b' : ($ppp['status_key'] === 'selling' ? '#1d4ed8' : ($ppp['status_key'] === 'children' ? '#6d28d9' : '#92400e'))); ?>; border-radius:999px; padding:6px 10px; font-size:11px; font-weight:700; line-height:1.2;">
                                <?php echo esc_html($ppp['status_label']); ?>
                            </span>
                        </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" value="<?php echo esc_attr($row_purchase > 0 ? number_format($row_purchase, 2, '.', '') : ''); ?>" data-role="purchase" placeholder="0.00" style="width:100%; padding:8px 10px; border:1px solid #d1d5db; border-radius:8px; font-size:14px;">
                        </td>
                        <td>
                            <input type="number" step="0.01" min="0.01" value="<?php echo esc_attr($row_selling > 0 ? number_format($row_selling, 2, '.', '') : ''); ?>" data-role="selling" placeholder="0.00" style="width:100%; padding:8px 10px; border:1px solid #d1d5db; border-radius:8px; font-size:14px;">
                        </td>
                        <td>
                            <div style="display:flex; align-items:center; gap:6px;">
                                <input type="number" step="0.01" min="0" max="99.99" value="<?php echo esc_attr($row_selling > 0 ? number_format($row_margin, 2, '.', '') : ''); ?>" data-role="margin" placeholder="0.00" style="width:88px; padding:8px 10px; border:1px solid #d1d5db; border-radius:8px; font-size:14px;">
                                <span style="font-size:12px; font-weight:700; color:#64748b;">%</span>
                            </div>
                        </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>
                            <?php if ($is_variable): ?>
                            <label style="display:flex; align-items:center; gap:4px; margin-top:6px; font-size:11px; color:#6b7280; cursor:pointer;">
                                <input type="checkbox" data-role="apply-all" checked style="margin:0;">
                                <?php echo esc_html(bizmart_text('Apply to all variations', 'Appliquer à toutes les variations', 'تطبيق على جميع المتغيرات')); ?>
                            </label>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php if ($is_variable && !empty($var_rows)): ?>
                    <?php foreach ($var_rows as $variation_row):
                        $variation_purchase = (float) ($variation_row['purchase_price'] ?? 0);
                        $variation_selling = (float) ($variation_row['selling_price'] ?? 0);
                        $variation_margin = $variation_selling > 0 ? round((($variation_selling - $variation_purchase) / $variation_selling) * 100, 2) : 0;
                    ?>
                    <tr class="biz-var-subrow biz-var-subrow-<?php echo intval($ppp['id']); ?>" data-missing-pricing-row data-row-kind="variation" data-product-id="<?php echo intval($variation_row['id']); ?>" data-parent-id="<?php echo intval($ppp['id']); ?>" data-group-id="<?php echo intval($ppp['id']); ?>" data-countable="0" style="display:none; background:#eff6ff;">
                        <td style="padding-left:28px;">
                            <div style="font-size:13px; color:#4b5563;">↳ <a href="#" onclick="openProductPopup(<?php echo intval($variation_row['id']); ?>); return false;" style="color:#4b5563; text-decoration:none; font-weight:600;"><?php echo esc_html($variation_row['name']); ?></a></div>
                        </td>
                        <td>
                            <span data-role="status-badge" data-status-key="<?php echo esc_attr($variation_row['status_key']); ?>" style="display:inline-flex; align-items:center; gap:6px; background:<?php echo esc_attr($variation_row['status_key'] === 'both' ? '#fee2e2' : ($variation_row['status_key'] === 'selling' ? '#dbeafe' : '#fef3c7')); ?>; color:<?php echo esc_attr($variation_row['status_key'] === 'both' ? '#991b1b' : ($variation_row['status_key'] === 'selling' ? '#1d4ed8' : '#92400e')); ?>; border-radius:999px; padding:6px 10px; font-size:11px; font-weight:700; line-height:1.2;">
                                <?php echo esc_html($variation_row['status_label']); ?>
                            </span>
                        </td>
                        <td>
                            <code style="background:#f3f4f6; padding:2px 6px; border-radius:4px; font-size:10px; color:#6b7280;"><?php echo esc_html($variation_row['sku'] ?: '—'); ?></code>
                        </td>
                        <td>
                            <input type="number" step="0.01" min="0" value="<?php echo esc_attr($variation_purchase > 0 ? number_format($variation_purchase, 2, '.', '') : ''); ?>" data-role="purchase" placeholder="0.00" style="width:100%; padding:6px 10px; border:1px solid #dbe2ea; border-radius:6px; font-size:13px;">
                        </td>
                        <td>
                            <input type="number" step="0.01" min="0.01" value="<?php echo esc_attr($variation_selling > 0 ? number_format($variation_selling, 2, '.', '') : ''); ?>" data-role="selling" placeholder="0.00" style="width:100%; padding:6px 10px; border:1px solid #dbe2ea; border-radius:6px; font-size:13px;">
                        </td>
                        <td>
                            <div style="display:flex; align-items:center; gap:6px;">
                                <input type="number" step="0.01" min="0" max="99.99" value="<?php echo esc_attr($variation_selling > 0 ? number_format($variation_margin, 2, '.', '') : ''); ?>" data-role="margin" placeholder="0.00" style="width:88px; padding:6px 10px; border:1px solid #dbe2ea; border-radius:6px; font-size:13px;">
                                <span style="font-size:12px; font-weight:700; color:#64748b;">%</span>
                            </div>
                        </td>
                        <td>
                            <button onclick="saveQuickPrice(<?php echo intval($variation_row['id']); ?>)" 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; ?>
                    <?php 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 and selling prices.', 'Tous les produits ont des prix d\'achat et de vente.', 'كل المنتجات لديها أسعار شراء وبيع.')); ?></p>
            </div>
            <?php endif; ?>
            <div id="biz-missing-pricing-empty" style="display:none; text-align:center; padding:36px 12px; color:#64748b; font-weight:600;">
                <?php echo esc_html(bizmart_text('No incomplete pricing remains in this list.', 'Aucune tarification incomplète ne reste dans cette liste.', 'لم تعد هناك أسعار ناقصة في هذه القائمة.')); ?>
            </div>
        </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', 'Modifier', 'تعديل')); ?></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>

<!-- Dashboard Price History script moved to admin-dashboard.js -->
<?php })(); ?>
