<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();
$users = getAllUsers();

$totalUsers = count($users);
$s = getAdminDashboardStats();
$totalOrders  = $s['total_orders'];
$totalSuccess = $s['total_success'];
$totalPending = $s['total_pending'];
$totalFailed  = $s['total_failed'];
$totalRevenue = $s['total_revenue'];

$recentOrders = getRecentOrders(10);
$usersById = [];
foreach ($users as $u) { $usersById[$u['id']] = migrateUserSchema($u); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Admin Overview — FamGateway"; include __DIR__ . '/admin-style.php'; ?>
</head>
<body>
<?php include __DIR__ . '/admin-nav.php'; ?>
    <div class="wrap">

      <!-- Page Title -->
      <div style="margin-bottom:24px;">
        <h1 style="font-size:22px;font-weight:700;color:var(--color-ink);letter-spacing:-0.5px;display:flex;align-items:center;gap:8px;">
          <i data-lucide="shield-check" style="color:#ef4444;width:24px;height:24px;"></i> Admin Overview
        </h1>
        <p style="font-size:13px;color:var(--color-ink-mute);margin-top:4px;">Real-time gateway analytics, UPI processing stats and user accounts.</p>
      </div>

      <?php if (isset($_GET['msg']) && $_GET['msg'] === 'optimized'): ?>
      <div style="background:#ecfdf5;border:1px solid #a7f3d0;color:#059669;padding:12px 16px;border-radius:8px;margin-bottom:24px;font-size:14px;font-weight:500;display:flex;align-items:center;gap:8px;">
          <i data-lucide="check-circle-2" style="width:18px;height:18px;"></i> Database tables optimized successfully!
      </div>
      <?php endif; ?>

      <!-- STAT CARDS -->
      <div class="stat-grid">
        <div class="stat-card featured">
          <div class="stat-card-top">
            <div class="stat-card-label">Total Revenue</div>
            <div class="stat-card-icon"><i data-lucide="indian-rupee" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum">₹<?= number_format($totalRevenue, 2) ?></div>
        </div>
        <div class="stat-card">
          <div class="stat-card-top">
            <div class="stat-card-label">Total API Users</div>
            <div class="stat-card-icon purple"><i data-lucide="users" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum"><?= number_format($totalUsers) ?></div>
        </div>
        <div class="stat-card">
          <div class="stat-card-top">
            <div class="stat-card-label">Total Orders</div>
            <div class="stat-card-icon blue"><i data-lucide="shopping-cart" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum"><?= number_format($totalOrders) ?></div>
        </div>
        <div class="stat-card">
          <div class="stat-card-top">
            <div class="stat-card-label">Successful</div>
            <div class="stat-card-icon green"><i data-lucide="check-circle-2" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum"><?= number_format($totalSuccess) ?></div>
        </div>
        <div class="stat-card">
          <div class="stat-card-top">
            <div class="stat-card-label">Pending</div>
            <div class="stat-card-icon orange"><i data-lucide="clock" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum"><?= number_format($totalPending) ?></div>
        </div>
        <div class="stat-card">
          <div class="stat-card-top">
            <div class="stat-card-label">Failed / Expired</div>
            <div class="stat-card-icon red"><i data-lucide="x-circle" style="width:17px;height:17px;"></i></div>
          </div>
          <div class="stat-card-value tnum"><?= number_format($totalFailed) ?></div>
        </div>
      </div>

      <!-- BOTTOM GRID: Recent Orders + Quick Actions -->
      <div class="dashboard-bottom-grid">

        <!-- Recent Orders -->
        <div class="card" style="padding:0;overflow:hidden;margin-bottom:0;">
          <div style="padding:22px 28px 18px;">
            <div class="card-title"><i data-lucide="list" style="width:18px;height:18px;color:var(--color-primary);"></i> Recent API Orders</div>
            <div class="card-sub">Latest 10 transactions across all user accounts</div>
          </div>
          <div class="table-container" style="margin:0;border-radius:0 0 var(--r-xl) var(--r-xl);">
            <table class="table">
              <thead>
                <tr>
                  <th>Order ID</th>
                  <th>User</th>
                  <th>Amount</th>
                  <th>Status</th>
                  <th>Date</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($recentOrders)): ?>
                <tr><td colspan="5">
                  <div class="empty-state">
                    <div class="empty-state-icon"><i data-lucide="inbox"></i></div>
                    <div class="empty-state-title">No transactions yet</div>
                    <div class="empty-state-sub">Transactions will appear here once users start using the API</div>
                  </div>
                </td></tr>
                <?php else: foreach ($recentOrders as $ro):
                  $uName = 'Guest (Demo)';
                  if (!empty($ro['user_id']) && isset($usersById[$ro['user_id']])) $uName = $usersById[$ro['user_id']]['name'];
                ?>
                <tr>
                  <td class="tnum" style="font-weight:600;color:var(--blue-700);font-size:12px;"><?= htmlspecialchars($ro['order_id']) ?></td>
                  <td style="font-weight:500;"><?= htmlspecialchars($uName) ?></td>
                  <td class="tnum" style="font-weight:700;">₹<?= number_format($ro['amount'], 2) ?></td>
                  <td>
                    <?php if($ro['status']==='success'): ?><span class="badge badge-success">Paid</span>
                    <?php elseif($ro['status']==='pending'): ?><span class="badge badge-warning">Pending</span>
                    <?php else: ?><span class="badge badge-danger">Failed</span><?php endif; ?>
                  </td>
                  <td style="color:var(--color-ink-mute);font-size:12px;"><?= htmlspecialchars(date('M d, Y h:i A', strtotime($ro['created_at']))) ?></td>
                </tr>
                <?php endforeach; endif; ?>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Quick Actions -->
        <div style="display:flex;flex-direction:column;gap:16px;">
          <div class="card" style="margin-bottom:0;">
            <div class="card-title" style="margin-bottom:14px;"><i data-lucide="zap" style="width:18px;height:18px;color:#f59e0b;"></i> Quick Actions</div>
            <div style="display:flex;flex-direction:column;gap:8px;">
              <a href="users.php" class="btn btn-secondary" style="justify-content:flex-start;width:100%;"><i data-lucide="users" style="width:15px;height:15px;"></i> Manage Users</a>
              <a href="settings.php" class="btn btn-secondary" style="justify-content:flex-start;width:100%;"><i data-lucide="settings" style="width:15px;height:15px;"></i> Gateway Settings</a>
              <a href="optimize-database.php" class="btn btn-secondary" style="justify-content:flex-start;width:100%;"><i data-lucide="database" style="width:15px;height:15px;"></i> Optimize Database</a>
              <a href="../index.php" class="btn btn-secondary" style="justify-content:flex-start;width:100%;" target="_blank"><i data-lucide="external-link" style="width:15px;height:15px;"></i> View Website</a>
            </div>
          </div>
          <div class="card" style="margin-bottom:0;background:linear-gradient(135deg,#0f172a,#1e3a8a);border:none;">
            <div style="font-weight:700;font-size:14px;color:#fff;margin-bottom:8px;display:flex;align-items:center;gap:8px;">
              <i data-lucide="shield-alert" style="color:#ef4444;width:18px;height:18px;"></i> System Health
            </div>
            <p style="font-size:12.5px;color:#94a3b8;line-height:1.6;margin-bottom:12px;">All API webhooks and transaction endpoints are operational.</p>
            <div style="display:flex;align-items:center;gap:8px;font-size:12px;font-weight:600;color:#34d399;">
              <span style="width:7px;height:7px;border-radius:50%;background:#34d399;display:inline-block;box-shadow:0 0 8px #34d399;"></span> Gateway Online
            </div>
          </div>
        </div>

      </div>
    </div>
  </main>
</div>
<script>if (window.lucide) { lucide.createIcons(); }</script>
</body>
</html>
