<?php
$overview = $overview ?? [];
$overviewCards = $overview['cards'] ?? [];
$overviewStats = $overview['stats'] ?? [];
$trendData = $trend ?? [];
$warningsSummary = $warnings ?? [];
$reportsSummary = $reports ?? [];
$transactionsSummary = $transactions ?? [];
$recentWarnings = $recentWarnings ?? [];
$recentTickRequests = $recentTickRequests ?? [];
$recentTransactions = $recentTransactions ?? [];
$topCreators = $topCreators ?? [];
$recentUsers = $recentUsers ?? [];
$currentUserName = $currentUserName ?? 'Admin';
$generatedAt = isset($generatedAt) ? (int)$generatedAt : time();

if (!function_exists('dashboard_format_number')) {
    function dashboard_format_number($value, int $decimals = 0): string
    {
        $value = (float)$value;
        if ($decimals === 0) {
            return number_format($value);
        }
        return number_format($value, $decimals);
    }
}

if (!function_exists('dashboard_relative_time')) {
    function dashboard_relative_time($timestamp): string
    {
        if (empty($timestamp)) {
            return '—';
        }
        $timestamp = (int)$timestamp;
        if ($timestamp > 1000000000000) {
            $timestamp = (int)round($timestamp / 1000);
        }
        $now = time();
        $diff = max(0, $now - $timestamp);
        if ($diff < 60) {
            return $diff . 's ago';
        }
        if ($diff < 3600) {
            return floor($diff / 60) . 'm ago';
        }
        if ($diff < 86400) {
            return floor($diff / 3600) . 'h ago';
        }
        if ($diff < 604800) {
            return floor($diff / 86400) . 'd ago';
        }
        return date('M j, Y', $timestamp);
    }
}

if (!function_exists('dashboard_status_badge')) {
    function dashboard_status_badge(string $status): array
    {
        $statusKey = strtolower($status);
        $map = [
            'pending'   => ['label' => 'Pending', 'class' => 'bg-warning-soft text-warning'],
            'processing'=> ['label' => 'Processing', 'class' => 'bg-info-soft text-info'],
            'approved'  => ['label' => 'Approved', 'class' => 'bg-success-soft text-success'],
            'completed' => ['label' => 'Completed', 'class' => 'bg-success-soft text-success'],
            'resolved'  => ['label' => 'Resolved', 'class' => 'bg-success-soft text-success'],
            'closed'    => ['label' => 'Closed', 'class' => 'bg-secondary-soft text-secondary'],
            'active'    => ['label' => 'Active', 'class' => 'bg-danger-soft text-danger'],
            'blocked'   => ['label' => 'Blocked', 'class' => 'bg-danger-soft text-danger'],
            'failed'    => ['label' => 'Failed', 'class' => 'bg-danger-soft text-danger'],
            'rejected'  => ['label' => 'Rejected', 'class' => 'bg-danger-soft text-danger'],
            'request'   => ['label' => 'Request', 'class' => 'bg-primary-soft text-primary'],
            'open'      => ['label' => 'Open', 'class' => 'bg-info-soft text-info'],
        ];

        return $map[$statusKey] ?? ['label' => ucfirst($statusKey ?: 'Open'), 'class' => 'bg-secondary-soft text-secondary'];
    }
}
?>

<main class="main-wrapper">
  <div class="main-content dashboard-page">
    <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between mb-4">
      <div>
        <h2 class="dashboard-title mb-1">Welcome back, <?php echo htmlspecialchars($currentUserName); ?>!</h2>
        <p class="text-muted mb-0">Snapshot as of <?php echo date('M j, Y \a\t g:i A', $generatedAt); ?></p>
      </div>
      <div class="text-md-end mt-3 mt-md-0">
        <span class="badge rounded-pill bg-primary-soft text-primary me-2">
          <i class="bi bi-check2-circle me-1"></i><?php echo isset($overviewStats['activeRate']) ? $overviewStats['activeRate'] : 0; ?>% active rate
        </span>
        <span class="badge rounded-pill bg-warning-soft text-warning">
          <i class="bi bi-exclamation-triangle me-1"></i><?php echo isset($overviewStats['warningRate']) ? $overviewStats['warningRate'] : 0; ?>% users with warnings
        </span>
      </div>
    </div>
<?php 

//print_r($overviewCards);
?>
    <div class="row g-3 mb-3">
      <?php if (!empty($overviewCards)): ?>
        <?php foreach ($overviewCards as $card): ?>
          <div class="col-xl-3 col-md-6">
            <a href="<?php echo $card['link']; ?>" class="text-decoration-none d-block h-100">
              <div class="card metric-card shadow-sm border-0 h-100">
                <div class="card-body">
                  <div class="d-flex align-items-start justify-content-between">
                    <div>
                      <span class="metric-title text-muted"><?php echo htmlspecialchars($card['title']); ?></span>
                      <h3 class="metric-value mb-1"><?php echo dashboard_format_number($card['value']); ?></h3>
                      <span class="metric-subtitle text-muted"><?php echo htmlspecialchars($card['description']); ?></span>
                    </div>
                    <span class="metric-icon <?php echo htmlspecialchars('icon-' . ($card['variant'] ?? 'primary')); ?>">
                      <i class="bi <?php echo htmlspecialchars($card['icon'] ?? 'bi-graph-up'); ?>"></i>
                    </span>
                  </div>
                </div>
              </div>
            </a>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <div class="row g-3 mb-3">
      <div class="col-12">
        <div class="card shadow-sm border-0 h-100">
          <div class="card-header bg-white border-0">
            <h6 class="mb-0">Warnings Summary</h6>
            <small class="text-muted">Last update <?php echo dashboard_relative_time($generatedAt); ?></small>
          </div>
          <div class="card-body">
            <?php 
              $warningsSummary = $warningsSummary ?? [];
              $recentWarnings = $recentWarnings ?? [];
            ?>
            <div class="row g-2 mb-3">
              <div class="col-sm-6 col-lg-3">
                <div class="stat-pill bg-primary-soft text-primary">
                  <span class="label">Total</span>
                  <span class="value"><?php echo dashboard_format_number($warningsSummary['total'] ?? 0); ?></span>
                </div>
              </div>
              <div class="col-sm-6 col-lg-3">
                <div class="stat-pill bg-danger-soft text-danger">
                  <span class="label">Active</span>
                  <span class="value"><?php echo dashboard_format_number($warningsSummary['active'] ?? 0); ?></span>
                </div>
              </div>
              <div class="col-sm-6 col-lg-3">
                <div class="stat-pill bg-success-soft text-success">
                  <span class="label">Resolved</span>
                  <span class="value"><?php echo dashboard_format_number($warningsSummary['resolved'] ?? 0); ?></span>
                </div>
              </div>
              <div class="col-sm-6 col-lg-3">
                <div class="stat-pill bg-warning-soft text-warning">
                  <span class="label">Auto-blocks</span>
                  <span class="value"><?php echo dashboard_format_number($warningsSummary['autoBlocksToday'] ?? 0); ?></span>
                </div>
              </div>
            </div>
            <h6 class="fw-semibold mb-3">Recent Warned Users</h6>
            <div class="list-group list-group-flush custom-scroll">
              <?php if (!empty($recentWarnings) && is_array($recentWarnings)): ?>
                <?php foreach ($recentWarnings as $warning): ?>
                  <?php 
                    if (!is_array($warning)) continue;
                    $fullName = !empty($warning['fullName']) ? $warning['fullName'] : (!empty($warning['userName']) ? $warning['userName'] : (isset($warning['user']) ? $warning['user'] : 'Unknown User'));
                    $userName = isset($warning['userName']) && !empty($warning['userName']) ? $warning['userName'] : '';
                    $userValue = isset($warning['user']) ? (string)$warning['user'] : '';
                    $userEmail = !empty($userValue) && filter_var($userValue, FILTER_VALIDATE_EMAIL) ? $userValue : '';
                    $warningCount = isset($warning['occurrences']) ? (int)$warning['occurrences'] : 0;
                    $lastWarning = isset($warning['lastOccurrence']) ? (int)$warning['lastOccurrence'] : 0;
                  ?>
                  <div class="list-group-item px-0">
                    <div class="d-flex justify-content-between align-items-start">
                      <div class="flex-grow-1">
                        <div class="fw-semibold"><?php echo htmlspecialchars($fullName); ?></div>
                        <small class="text-muted">
                          <?php if (!empty($userName)): ?>
                            <i class="bi bi-at me-1"></i><?php echo htmlspecialchars($userName); ?>
                            <?php if (!empty($userEmail)): ?> • <?php endif; ?>
                          <?php endif; ?>
                          <?php if (!empty($userEmail)): ?>
                            <i class="bi bi-envelope me-1"></i><?php echo htmlspecialchars($userEmail); ?>
                          <?php endif; ?>
                          <?php if ($lastWarning > 0): ?>
                            • <i class="bi bi-clock me-1"></i><?php echo dashboard_relative_time($lastWarning); ?>
                          <?php endif; ?>
                        </small>
                      </div>
                      <span class="badge bg-warning text-dark">
                        <i class="bi bi-exclamation-triangle me-1"></i><?php echo dashboard_format_number($warningCount); ?> warning<?php echo $warningCount !== 1 ? 's' : ''; ?>
                      </span>
                    </div>
                  </div>
                <?php endforeach; ?>
              <?php else: ?>
                <div class="text-center text-muted py-3">No warned users found.</div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="row g-3 mb-3">
      <div class="col-xl-4">
        <div class="card shadow-sm border-0 h-100">
          <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
            <div>
              <h6 class="mb-0">Reports &amp; Incidents</h6>
              <small class="text-muted">Tracking platform safety</small>
            </div>
            <span class="badge bg-info-soft text-info">Total: <?php echo dashboard_format_number($reportsSummary['total'] ?? 0); ?></span>
          </div>
          <div class="card-body">
            <div class="d-flex gap-3 mb-3">
              <div>
                <span class="text-muted d-block small">Open</span>
                <span class="fw-semibold fs-5"><?php echo dashboard_format_number($reportsSummary['open'] ?? 0); ?></span>
              </div>
              <div>
                <span class="text-muted d-block small">Resolved</span>
                <span class="fw-semibold fs-5 text-success"><?php echo dashboard_format_number($reportsSummary['resolved'] ?? 0); ?></span>
              </div>
            </div>
            <div class="list-group list-group-flush custom-scroll">
              <?php if (!empty($reportsSummary['recent'])): ?>
                <?php foreach ($reportsSummary['recent'] as $report): ?>
                  <?php $badge = dashboard_status_badge($report['status'] ?? 'open'); ?>
                  <div class="list-group-item px-0">
                    <div class="d-flex justify-content-between align-items-start">
                      <div>
                        <div class="fw-semibold"> Report : <?php  echo htmlspecialchars($report['title'] ?? 'Report'); ?></div>
                        <small class="text-muted">By <?php echo htmlspecialchars($report['reporter'] ?? 'Unknown'); ?> • <?php echo dashboard_relative_time($report['createdAt'] ?? 0); ?></small>
                      </div>
                      <span class="badge <?php echo htmlspecialchars($badge['class']); ?>"><?php echo htmlspecialchars($badge['label']); ?></span>
                    </div>
                  </div>
                <?php endforeach; ?>
              <?php else: ?>
                <div class="text-center text-muted py-3">No recent reports.</div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-4">
        <div class="card shadow-sm border-0 h-100">
          <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
            <div>
              <h6 class="mb-0">Blue Tick Requests</h6>
              <small class="text-muted">Awaiting review</small>
            </div>
            <span class="badge bg-primary-soft text-primary">Pending: <?php echo dashboard_format_number(count($recentTickRequests)); ?></span>
          </div>
          <div class="card-body">
            <div class="list-group list-group-flush custom-scroll">
              
              <?php if (!empty($recentTickRequests)): ?>
                <?php foreach ($recentTickRequests as $request): ?>
                  <div class="list-group-item px-0">
                    <div class="d-flex justify-content-between align-items-start">
                      <div>
                        <div class="fw-semibold"><?php echo htmlspecialchars($request['name'] ?? 'Unknown'); ?></div>
                        <small class="text-muted">@<?php echo htmlspecialchars($request['userName'] ?? 'user'); ?> • <?php echo dashboard_relative_time($request['requestDate'] ?? 0); ?></small>
                      </div>
                      <span class="badge bg-warning-soft text-warning">Pending</span>
                    </div>
                    <div class="small text-muted mt-1">
                      <?php if (!empty($request['followers'])): ?>
                        <span><i class="bi bi-people me-1"></i><?php echo dashboard_format_number($request['followers']); ?> followers</span>
                      <?php endif; ?>
                      <?php if (!empty($request['category'])): ?>
                        <span class="ms-2"><i class="bi bi-tags me-1"></i><?php echo htmlspecialchars($request['category']); ?></span>
                      <?php endif; ?>
                    </div>
                  </div>
                <?php endforeach; ?>
              <?php else: ?>
                <div class="text-center text-muted py-3">No pending requests.</div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-4">
        <div class="card shadow-sm border-0 h-100">
          <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
            <div>
              <h6 class="mb-0">Financial Activity</h6>
              <small class="text-muted">Withdrawals &amp; payouts</small>
            </div>
            <span class="badge bg-success-soft text-success">Processed today: <?php echo dashboard_format_number($transactionsSummary['processedToday'] ?? 0); ?></span>
          </div>
          <div class="card-body">
            <div class="d-flex gap-3 mb-3">
              <div>
                <span class="text-muted d-block small">Total</span>
                <span class="fw-semibold fs-5"><?php echo dashboard_format_number($transactionsSummary['total'] ?? 0); ?></span>
              </div>
              <div>
                <span class="text-muted d-block small">Pending</span>
                <span class="fw-semibold fs-5 text-warning"><?php echo dashboard_format_number($transactionsSummary['pending'] ?? 0); ?></span>
              </div>
              <div>
                <span class="text-muted d-block small">Coins</span>
                <span class="fw-semibold fs-5 text-primary"><?php echo dashboard_format_number($overviewStats['totalCoins'] ?? 0); ?></span>
              </div>
            </div>
            <div class="list-group list-group-flush custom-scroll">
              <?php if (!empty($recentTransactions)): ?>
                <?php foreach ($recentTransactions as $transaction): ?>
                  <?php $badge = dashboard_status_badge($transaction['status'] ?? 'pending'); ?>
                  <div class="list-group-item px-0">
                    <div class="d-flex justify-content-between align-items-start">
                      <div>
                        <div class="fw-semibold">$<?php echo number_format($transaction['amount'] ?? 0, 2); ?></div>
                        <small class="text-muted"><?php echo htmlspecialchars($transaction['userName'] ?? 'Unknown'); ?> • <?php echo dashboard_relative_time($transaction['createdAt'] ?? 0); ?></small>
                      </div>
                      <span class="badge <?php echo htmlspecialchars($badge['class']); ?>"><?php echo htmlspecialchars($badge['label']); ?></span>
                    </div>
                  </div>
                <?php endforeach; ?>
              <?php else: ?>
                <div class="text-center text-muted py-3">No recent transactions.</div>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="row g-3">
      <div class="col-lg-6">
        <div class="card shadow-sm border-0 h-100">
          <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
            <h6 class="mb-0">Top Creators by Coins</h6>
            <span class="badge bg-primary-soft text-primary">Top 5</span>
          </div>
          <div class="card-body table-responsive">
            <?php if (!empty($topCreators)): ?>
              <table class="table align-middle mb-0">
                <thead>
                  <tr>
                    <th>User</th>
                    <th class="text-end">Coins</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($topCreators as $creator): ?>
                    <tr>
                      <td>
                        <div class="fw-semibold"><?php echo htmlspecialchars($creator['name'] ?? 'Unknown'); ?></div>
                        <small class="text-muted">@<?php echo htmlspecialchars($creator['userName'] ?? 'user'); ?></small>
                      </td>
                      <td class="text-end">
                        <span class="badge bg-primary-soft text-primary"><i class="bi bi-coin me-1"></i><?php echo dashboard_format_number($creator['coins'] ?? 0); ?></span>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            <?php else: ?>
              <div class="text-center text-muted py-4">No coin activity recorded yet.</div>
            <?php endif; ?>
          </div>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="card shadow-sm border-0 h-100">
          <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
            <h6 class="mb-0">Newest Members</h6>
            <span class="badge bg-success-soft text-success">Last 6 joins</span>
          </div>
          <div class="card-body table-responsive">
            <?php if (!empty($recentUsers)): ?>
              <table class="table align-middle mb-0">
                <thead>
                  <tr>
                    <th>User</th>
                    <th>Warnings</th>
                    <th class="text-end">Joined</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($recentUsers as $user): ?>
                    <tr>
                      <td>
                        <div class="fw-semibold"><?php echo htmlspecialchars($user['name'] ?? 'Unknown'); ?></div>
                        <small class="text-muted">@<?php echo htmlspecialchars($user['userName'] ?? 'user'); ?></small>
                      </td>
                      <td>
                        <span class="badge <?php echo ($user['warnings'] ?? 0) > 0 ? 'bg-danger-soft text-danger' : 'bg-secondary-soft text-secondary'; ?>"><?php echo dashboard_format_number($user['warnings'] ?? 0); ?></span>
                      </td>
                      <td class="text-end"><small class="text-muted"><?php echo dashboard_relative_time($user['joinDate'] ?? 0); ?></small></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            <?php else: ?>
              <div class="text-center text-muted py-4">No new users joined recently.</div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<style>
  .dashboard-page {
    padding: 1.5rem;
  }
  .dashboard-title {
    font-weight: 600;
  }
  .metric-card {
    border-radius: 1rem;
  }
  .metric-title {
    font-size: 0.875rem;
    font-weight: 500;
  }
  .metric-value {
    font-weight: 700;
  }
  .metric-subtitle {
    font-size: 0.875rem;
  }
  .metric-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    border-radius: 14px;
    font-size: 1.5rem;
  }
  .icon-primary { background: rgba(79, 70, 229, 0.12); color: #4f46e5; }
  .icon-success { background: rgba(16, 185, 129, 0.12); color: #10b981; }
  .icon-warning { background: rgba(251, 191, 36, 0.16); color: #d97706; }
  .icon-info { background: rgba(14, 165, 233, 0.12); color: #0ea5e9; }
  .stat-pill {
    border-radius: 12px;
    padding: 0.75rem 1rem;
  }
  .stat-pill .label {
    display: block;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
  }
  .stat-pill .value {
    font-weight: 600;
    font-size: 1.125rem;
  }
  .custom-scroll {
    max-height: 280px;
    overflow-y: auto;
  }
  .custom-scroll::-webkit-scrollbar {
    width: 6px;
  }
  .custom-scroll::-webkit-scrollbar-thumb {
    background: rgba(148, 163, 184, 0.5);
    border-radius: 12px;
  }
  .bg-primary-soft { background: rgba(79, 70, 229, 0.12) !important; }
  .bg-success-soft { background: rgba(16, 185, 129, 0.12) !important; }
  .bg-warning-soft { background: rgba(251, 191, 36, 0.20) !important; }
  .bg-danger-soft { background: rgba(239, 68, 68, 0.15) !important; }
  .bg-info-soft { background: rgba(14, 165, 233, 0.15) !important; }
  .bg-secondary-soft { background: rgba(107, 114, 128, 0.15) !important; }
  .badge {
    font-weight: 500;
  }
</style>

