<?php
/**
 * Seller Sales Metrics Cards (FIXED VERSION)
 */

if (!isset($pdo) || !isset($seller_order_lookup_id)) {
    return;
}

// Time ranges
$todayStart     = date('Y-m-d 00:00:00');
$todayEnd       = date('Y-m-d 23:59:59');

$thisMonthStart = date('Y-m-01 00:00:00');
$thisMonthEnd   = date('Y-m-t 23:59:59');

$prevMonthStart = date('Y-m-01 00:00:00', strtotime('first day of last month'));
$prevMonthEnd   = date('Y-m-t 23:59:59', strtotime('last day of last month'));

// Metrics structure
$metricsMatrix = [
    'all'   => ['sold' => 0, 'net' => 0.0],
    'today' => ['sold' => 0, 'net' => 0.0],
    'month' => ['sold' => 0, 'net' => 0.0],
    'prev'  => ['sold' => 0, 'net' => 0.0]
];

// FETCH ONLY PAID ORDERS FOR THIS SELLER
$stmt = $pdo->prepare("
    SELECT net_seller_income, created_at
    FROM orders
    WHERE seller_id = ?
    AND payment_status = 'Paid'
");
$stmt->execute([$seller_order_lookup_id]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// LOOP
foreach ($orders as $order) {

    $net = (float)$order['net_seller_income'];
    $time = $order['created_at'];

    // ALL TIME
    $metricsMatrix['all']['sold']++;
    $metricsMatrix['all']['net'] += $net;

    // TODAY
    if ($time >= $todayStart && $time <= $todayEnd) {
        $metricsMatrix['today']['sold']++;
        $metricsMatrix['today']['net'] += $net;
    }

    // THIS MONTH
    if ($time >= $thisMonthStart && $time <= $thisMonthEnd) {
        $metricsMatrix['month']['sold']++;
        $metricsMatrix['month']['net'] += $net;
    }

    // PREVIOUS MONTH
    if ($time >= $prevMonthStart && $time <= $prevMonthEnd) {
        $metricsMatrix['prev']['sold']++;
        $metricsMatrix['prev']['net'] += $net;
    }
}

$activeCurrency = currency_symbol();
?>

<div class="grid grid-cols-1 md:grid-cols-3 gap-5 mb-8 items-end">

    <!-- SOLD -->
    <div class="glass-card p-6 rounded-2xl border border-slate-800/80 shadow-xl flex items-center justify-between group">
        <div>
            <p class="text-xs font-bold uppercase text-nftTextGray">Total Products Sold</p>
            <h3 id="uiMetricCardSoldValueDisplay" class="text-3xl font-black text-white font-mono">
                <?php echo number_format($metricsMatrix['all']['sold']); ?>
            </h3>
        </div>
    </div>

    <!-- NET INCOME -->
    <div class="glass-card p-6 rounded-2xl border border-slate-800/80 shadow-xl flex items-center justify-between group">
        <div>
            <p class="text-xs font-bold uppercase text-nftTextGray">Total Net Income</p>
            <h3 id="uiMetricCardNetIncomeValueDisplay" class="text-3xl font-black text-emerald-400 font-mono">
                <?php echo htmlspecialchars(format_currency($metricsMatrix['all']['net']), ENT_QUOTES, 'UTF-8'); ?>
            </h3>
        </div>
    </div>

    <!-- FILTER -->
    <div class="glass-card p-5 rounded-2xl border border-slate-800/60 shadow-xl">
        <select id="realtimeAnalyticsTimeframeSelector" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white font-semibold">
            <option value="all">Lifetime History</option>
            <option value="today">Today</option>
            <option value="month">This Month</option>
            <option value="prev">Previous Month</option>
        </select>
    </div>

</div>

<script>
document.addEventListener("DOMContentLoaded", function () {

    const data = {
        all:   { sold: "<?= number_format($metricsMatrix['all']['sold']); ?>", net: "<?= htmlspecialchars(format_currency($metricsMatrix['all']['net']), ENT_QUOTES, 'UTF-8'); ?>" },
        today: { sold: "<?= number_format($metricsMatrix['today']['sold']); ?>", net: "<?= htmlspecialchars(format_currency($metricsMatrix['today']['net']), ENT_QUOTES, 'UTF-8'); ?>" },
        month: { sold: "<?= number_format($metricsMatrix['month']['sold']); ?>", net: "<?= htmlspecialchars(format_currency($metricsMatrix['month']['net']), ENT_QUOTES, 'UTF-8'); ?>" },
        prev:  { sold: "<?= number_format($metricsMatrix['prev']['sold']); ?>", net: "<?= htmlspecialchars(format_currency($metricsMatrix['prev']['net']), ENT_QUOTES, 'UTF-8'); ?>" }
    };

    const select = document.getElementById("realtimeAnalyticsTimeframeSelector");
    const soldEl = document.getElementById("uiMetricCardSoldValueDisplay");
    const netEl  = document.getElementById("uiMetricCardNetIncomeValueDisplay");

    select.addEventListener("change", function (e) {
        const key = e.target.value;
        if (data[key]) {
            soldEl.textContent = data[key].sold;
            netEl.textContent = data[key].net;
        }
    });

});
</script>
