<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$users = readJson(USERS_FILE);
$orders = readJson(ORDERS_FILE);

$totalUsers = count($users);
$todayStr = nowIST()->format('Y-m-d');

$todayAmount = 0;
$totalPayments = 0;
$totalRequests = 0;
$totalPending = 0;
$totalFailed = 0;
$totalReceivedAmount = 0;
$totalPendingAmount = 0;
$totalFailedAmount = 0;

$last7Days = [];
for ($i = 6; $i >= 0; $i--) {
    $d = (clone nowIST())->modify("-$i days")->format('Y-m-d');
    $last7Days[$d] = 0;
}

foreach ($orders as $order) {
    $totalRequests++;
    $orderDate = substr($order['created_at'] ?? '', 0, 10);

    if (($order['status'] ?? '') === 'success') {
        $totalPayments++;
        $amt = floatval($order['amount'] ?? 0);
        $totalReceivedAmount += $amt;
        if ($orderDate === $todayStr) {
            $todayAmount += $amt;
        }
        if (isset($last7Days[$orderDate])) {
            $last7Days[$orderDate] += $amt;
        }
    } elseif (($order['status'] ?? '') === 'pending') {
        $totalPending++;
        $totalPendingAmount += floatval($order['amount'] ?? 0);
    } else {
        $totalFailed++;
        $totalFailedAmount += floatval($order['amount'] ?? 0);
    }
}

$chartLabels = array_map(function($d) { return date('d M', strtotime($d)); }, array_keys($last7Days));
$chartValues = array_values($last7Days);

$pageTitle = 'Executive Overview';
$pageSub = 'Real-time revenue metrics, system health, and live transaction activity.';
include __DIR__ . '/../includes/admin_header.php';
?>

<div class="admin-wrap">
  <div class="stat-grid">
    <div class="stat-card primary">
      <div class="stat-label"><i class="fa-solid fa-users"></i> Total Registered Users</div>
      <div class="stat-value"><?= number_format($totalUsers) ?></div>
      <div class="stat-desc">Active gateway merchants</div>
    </div>
    <div class="stat-card primary">
      <div class="stat-label"><i class="fa-solid fa-receipt"></i> Total Transactions</div>
      <div class="stat-value" id="statTotalTx"><?= number_format($totalRequests) ?></div>
      <div class="stat-desc" id="statTodayTx"><?= number_format($totalPayments + $totalPending + $totalFailed) ?> all time · live sync</div>
    </div>
    <div class="stat-card">
      <div class="stat-label"><i class="fa-solid fa-calendar-day"></i> Received Today</div>
      <div class="stat-value up">₹<?= number_format($todayAmount, 2) ?></div>
      <div class="stat-desc">Direct to merchant FamPay</div>
    </div>
    <div class="stat-card">
      <div class="stat-label"><i class="fa-solid fa-wallet"></i> Total Volume</div>
      <div class="stat-value up">₹<?= number_format($totalReceivedAmount, 2) ?></div>
      <div class="stat-desc">0% commission processed</div>
    </div>
    <div class="stat-card">
      <div class="stat-label"><i class="fa-solid fa-circle-check"></i> Successful Payments</div>
      <div class="stat-value"><?= number_format($totalPayments) ?></div>
      <div class="stat-desc"><?= $totalRequests > 0 ? round(($totalPayments/$totalRequests)*100, 1) : 100 ?>% success rate</div>
    </div>
    <div class="stat-card">
      <div class="stat-label"><i class="fa-solid fa-clock-rotate-left"></i> Pending Volume</div>
      <div class="stat-value" style="color: var(--yellow)">₹<?= number_format($totalPendingAmount, 2) ?></div>
      <div class="stat-desc"><?= number_format($totalPending) ?> pending requests</div>
    </div>
  </div>

  <div class="card">
    <div class="card-title">
      <span><i class="fa-solid fa-chart-line"></i> Revenue Trend (7 Days)</span>
      <span class="badge-status success"><i class="fa-solid fa-bolt"></i> Live Financial Analytics</span>
    </div>
    <canvas id="revenueChart" height="90"></canvas>
  </div>

  <div class="card" style="margin-top:26px">
    <div style="display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap">
      <h2 class="card-title" style="margin-bottom:0"><i class="fa-solid fa-arrow-right"></i> Recent Activity</h2>
      <a href="transactions.php" style="color:#3b82f6;font-size:0.85rem;text-decoration:none;font-weight:600">View All Transactions <i class="fa-solid fa-arrow-right" style="font-size:0.7rem"></i></a>
    </div>
    <p style="color:var(--muted);font-size:0.88rem;margin-top:10px">Click <strong>Transactions</strong> in the top navigation to see all orders with search, filters, and pagination.</p>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script>
    const ctx = document.getElementById('revenueChart');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?= json_encode($chartLabels) ?>,
            datasets: [{
                label: 'Revenue Volume (₹)',
                data: <?= json_encode($chartValues) ?>,
                borderColor: '#3b82f6',
                backgroundColor: 'rgba(59, 130, 246, 0.15)',
                borderWidth: 3,
                fill: true,
                tension: 0.35,
                pointBackgroundColor: '#3b82f6',
                pointBorderColor: '#ffffff',
                pointRadius: 5,
                pointHoverRadius: 7
            }]
        },
        options: {
            responsive: true,
            plugins: { 
                legend: { labels: { color: '#94a3b8', font: { family: 'Inter', weight: 600 } } } 
            },
            scales: {
                x: { ticks: { color: '#94a3b8' }, grid: { color: 'rgba(255,255,255,0.05)' } },
                y: { ticks: { color: '#94a3b8' }, grid: { color: 'rgba(255,255,255,0.05)' } }
            }
        }
    });

</script>

<?php include __DIR__ . '/../includes/admin_footer.php'; ?>