<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'config.php';

// Validate session and set security headers
require_admin_session();

// ── Stats
$totalBrokers     = $dbh->query("SELECT COUNT(*) FROM brokers")->fetchColumn();
$totalBlacklisted = $dbh->query("SELECT COUNT(*) FROM blackbrokers")->fetchColumn();
$totalRegulators  = $dbh->query("SELECT COUNT(*) FROM broker_regulators")->fetchColumn();

// ── Heatmap top 3
$stmt = $dbh->prepare("SELECT name, overall_rating, score, broker_type FROM brokers ORDER BY score DESC LIMIT 3");
$stmt->execute();
$topBrokers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ── Recent brokers & blacklisted
$recentBrokers     = $dbh->query("SELECT name, score, broker_type, created_at FROM brokers ORDER BY created_at DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
$recentBlacklisted = $dbh->query("SELECT name, score, years_in_business, created_at FROM blackbrokers ORDER BY created_at DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);

// ── Include header (HTML head + navbar)
include "includes/header.php";

// ── Include sidebar
include "includes/sidebar.php";
?>

<!-- ══════════════════════════════════════════
     DASHBOARD STYLES
══════════════════════════════════════════ -->
<style>
  /* ── Page wrapper ── */
  .dash {
    max-width: 1380px;
    margin: 0 auto;
    padding: 30px 26px 0;
    position: relative;
    z-index: 1;
  }

  /* ── Fade-up animation ── */
  @keyframes fadeUp {
    from { opacity: 0; transform: translateY(18px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  .anim { animation: fadeUp 0.5s ease both; }
  .d1 { animation-delay: 0.04s; }
  .d2 { animation-delay: 0.10s; }
  .d3 { animation-delay: 0.16s; }
  .d4 { animation-delay: 0.22s; }
  .d5 { animation-delay: 0.28s; }
  .d6 { animation-delay: 0.34s; }

  /* ══════════════════════════
     PAGE HEADER
  ══════════════════════════ */
  .page-header {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    margin-bottom: 28px;
    flex-wrap: wrap;
    gap: 14px;
  }

  .ph-eyebrow {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.6rem;
    letter-spacing: 3.5px;
    text-transform: uppercase;
    color: var(--yellow-dim);
    margin-bottom: 6px;
    display: flex;
    align-items: center;
    gap: 7px;
  }
  .ph-eyebrow::before {
    content: '';
    display: inline-block;
    width: 20px; height: 2px;
    background: var(--yellow);
    border-radius: 2px;
  }

  .ph-title {
    font-family: 'Syne', sans-serif;
    font-size: 2rem;
    font-weight: 800;
    color: var(--text-1);
    letter-spacing: -0.5px;
    line-height: 1.1;
  }
  .ph-title strong { color: var(--yellow); }

  .ph-date {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.68rem;
    color: var(--text-3);
    background: var(--dark-700);
    border: 1px solid rgba(255,255,255,0.06);
    padding: 7px 14px;
    border-radius: 20px;
    display: flex;
    align-items: center;
    gap: 7px;
  }
  .ph-date i { color: var(--yellow); }

  /* ══════════════════════════
     STAT CARDS
  ══════════════════════════ */
  .stat-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 18px;
    margin-bottom: 24px;
  }

  .stat-card {
    background: var(--dark-700);
    border: 1px solid rgba(255,255,255,0.05);
    border-radius: 14px;
    padding: 24px 22px;
    position: relative;
    overflow: hidden;
    cursor: default;
    transition: transform 0.3s ease, box-shadow 0.3s ease, background 0.4s ease, border-color 0.4s ease;
  }
  .stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 18px 50px rgba(0,0,0,0.45);
  }

  :root.light-mode .stat-card {
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    border-color: rgba(0,0,0,0.08);
  }

  :root.light-mode .stat-card:hover {
    box-shadow: 0 8px 24px rgba(0,0,0,0.12);
  }

  /* Accent line on top */
  .stat-card::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 2px;
    background: var(--sc-accent, var(--yellow));
    border-radius: 14px 14px 0 0;
  }

  /* Background glow orb */
  .stat-card::after {
    content: '';
    position: absolute;
    top: -30px; right: -30px;
    width: 110px; height: 110px;
    border-radius: 50%;
    background: radial-gradient(circle, var(--sc-glow, var(--yellow-glow)) 0%, transparent 70%);
    pointer-events: none;
  }

  .stat-card.sc-blue   { --sc-accent: var(--blue);   --sc-glow: rgba(76,168,245,0.18); }
  .stat-card.sc-red    { --sc-accent: var(--red);    --sc-glow: rgba(239,79,74,0.18); }
  .stat-card.sc-green  { --sc-accent: var(--green);  --sc-glow: rgba(62,203,119,0.18); }

  .sc-icon {
    width: 42px; height: 42px;
    border-radius: 11px;
    display: flex; align-items: center; justify-content: center;
    font-size: 1rem;
    margin-bottom: 16px;
    position: relative;
    z-index: 1;
  }
  .stat-card.sc-blue  .sc-icon { background: rgba(76,168,245,0.12); color: var(--blue);  }
  .stat-card.sc-red   .sc-icon { background: rgba(239,79,74,0.12);  color: var(--red);   }
  .stat-card.sc-green .sc-icon { background: rgba(62,203,119,0.12); color: var(--green); }

  .sc-label {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.6rem;
    letter-spacing: 2.5px;
    text-transform: uppercase;
    color: var(--text-3);
    margin-bottom: 6px;
    position: relative; z-index: 1;
  }

  .sc-value {
    font-family: 'Syne', sans-serif;
    font-size: 2.7rem;
    font-weight: 800;
    color: var(--text-1);
    line-height: 1;
    margin-bottom: 10px;
    position: relative; z-index: 1;
  }

  .sc-tag {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.6rem;
    letter-spacing: 1px;
    padding: 3px 10px;
    border-radius: 20px;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    position: relative; z-index: 1;
  }
  .stat-card.sc-blue  .sc-tag { background: rgba(76,168,245,0.1);  color: var(--blue);  }
  .stat-card.sc-red   .sc-tag { background: rgba(239,79,74,0.1);   color: var(--red);   }
  .stat-card.sc-green .sc-tag { background: rgba(62,203,119,0.1);  color: var(--green); }

  /* ══════════════════════════
     MAIN 2-COL GRID
  ══════════════════════════ */
  .main-grid {
    display: grid;
    grid-template-columns: 1fr 360px;
    gap: 18px;
    margin-bottom: 24px;
  }

  /* ══════════════════════════
     PANEL (reusable card)
  ══════════════════════════ */
  .panel {
    background: var(--dark-700);
    border: 1px solid rgba(255,255,255,0.05);
    border-radius: 14px;
    overflow: hidden;
    transition: background 0.4s ease, border-color 0.4s ease, box-shadow 0.4s ease;
  }

  :root.light-mode .panel {
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    border-color: rgba(0,0,0,0.08);
  }

  .panel-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    border-bottom: 1px solid rgba(255,255,255,0.04);
    background: var(--dark-600);
    transition: background 0.4s ease, border-color 0.4s ease;
  }

  :root.light-mode .panel-head {
    border-bottom-color: rgba(0,0,0,0.06);
  }

  .panel-title {
    font-family: 'Syne', sans-serif;
    font-size: 0.88rem;
    font-weight: 700;
    color: var(--text-1);
    display: flex;
    align-items: center;
    gap: 9px;
  }
  .panel-title i { color: var(--yellow); font-size: 0.82rem; }

  .panel-pill {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.58rem;
    letter-spacing: 1.5px;
    text-transform: uppercase;
    background: var(--dark-500);
    color: var(--text-3);
    padding: 3px 9px;
    border-radius: 20px;
    border: 1px solid rgba(255,255,255,0.05);
  }

  /* ══════════════════════════
     DATA TABLE
  ══════════════════════════ */
  .data-table { width: 100%; border-collapse: collapse; }

  .data-table th {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.58rem;
    text-transform: uppercase;
    letter-spacing: 2px;
    color: var(--text-3);
    padding: 9px 18px;
    border-bottom: 1px solid rgba(255,255,255,0.04);
    font-weight: 400;
    text-align: left;
    background: var(--dark-600);
    white-space: nowrap;
    transition: background 0.4s ease, border-color 0.4s ease, color 0.4s ease;
  }

  .data-table td {
    padding: 12px 18px;
    font-size: 0.83rem;
    color: var(--text-1);
    border-bottom: 1px solid rgba(255,255,255,0.03);
    vertical-align: middle;
    transition: border-color 0.4s ease, background 0.4s ease, color 0.4s ease;
  }
  .data-table tr:last-child td { border-bottom: none; }
  .data-table tr:hover td { background: rgba(255,255,255,0.015); }

  :root.light-mode .data-table tr:hover td {
    background: rgba(245,197,24,0.08);
  }

  .td-score {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.7rem;
    padding: 2px 9px;
    border-radius: 20px;
    background: var(--yellow-glass);
    color: var(--yellow);
    border: 1px solid var(--yellow-border);
    display: inline-block;
  }

  .td-score.danger {
    background: rgba(239,79,74,0.09);
    color: var(--red);
    border-color: rgba(239,79,74,0.22);
  }

  .td-type {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.62rem;
    padding: 2px 8px;
    border-radius: 6px;
    background: rgba(255,255,255,0.05);
    color: var(--text-2);
    letter-spacing: 0.5px;
    display: inline-block;
  }

  .td-date {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.65rem;
    color: var(--text-3);
  }

  /* ══════════════════════════
     HEATMAP
  ══════════════════════════ */
  .heatmap-item {
    display: grid;
    grid-template-columns: 24px 1fr auto;
    gap: 12px;
    align-items: center;
    padding: 14px 20px;
    border-bottom: 1px solid rgba(255,255,255,0.03);
    transition: background 0.18s;
  }
  .heatmap-item:last-child { border-bottom: none; }
  .heatmap-item:hover { background: rgba(255,255,255,0.02); }

  .hm-rank {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.7rem;
    color: var(--text-3);
    font-weight: 500;
  }

  .hm-name {
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--text-1);
    margin-bottom: 3px;
  }

  .hm-meta {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
  }

  .hm-type {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.58rem;
    letter-spacing: 1px;
    text-transform: uppercase;
    color: var(--text-3);
  }

  .hm-bar {
    height: 3px;
    background: rgba(255,255,255,0.06);
    border-radius: 10px;
    overflow: hidden;
    max-width: 180px;
  }
  .hm-bar-fill {
    height: 100%;
    border-radius: 10px;
    width: 0%;
    transition: width 1.1s cubic-bezier(0.4,0,0.2,1);
  }
  .hm-bar-fill.bar-yellow { background: linear-gradient(90deg, var(--yellow-dim), var(--yellow)); }
  .hm-bar-fill.bar-orange { background: linear-gradient(90deg, #c06000, var(--orange)); }
  .hm-bar-fill.bar-red    { background: linear-gradient(90deg, #9b1212, var(--red)); }

  .hm-badge {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.6rem;
    letter-spacing: 1px;
    padding: 4px 10px;
    border-radius: 20px;
    white-space: nowrap;
    font-weight: 500;
  }
  .badge-trending { background: var(--yellow-glass); color: var(--yellow); border: 1px solid var(--yellow-border); }
  .badge-gaining  { background: rgba(245,160,32,0.1); color: var(--orange); border: 1px solid rgba(245,160,32,0.22); }
  .badge-flagged  { background: rgba(239,79,74,0.1); color: var(--red); border: 1px solid rgba(239,79,74,0.22); }

  /* ══════════════════════════
     CHARTS GRID
  ══════════════════════════ */
  .charts-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 18px;
    margin-bottom: 24px;
  }

  .chart-body {
    padding: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 240px;
  }

  /* ══════════════════════════
     RESPONSIVE
  ══════════════════════════ */
  @media (max-width: 1100px) {
    .main-grid { grid-template-columns: 1fr; }
  }
  @media (max-width: 820px) {
    .stat-grid   { grid-template-columns: 1fr 1fr; }
    .charts-grid { grid-template-columns: 1fr; }
  }
  @media (max-width: 560px) {
    .stat-grid { grid-template-columns: 1fr; }
    .dash      { padding: 18px 14px 0; }
    .ph-title  { font-size: 1.6rem; }
  }
</style>

<!-- ══════════════════════════════════════════
     DASHBOARD CONTENT
══════════════════════════════════════════ -->
<main class="dash">

  <!-- Page Header -->
  <div class="page-header anim d1">
    <div>
      <div class="ph-eyebrow">Admin Dashboard</div>
      <div class="ph-title">Welcome Back, <strong>Admin</strong></div>
    </div>
    <div class="ph-date">
      <i class="fas fa-calendar-alt"></i>
      <?= date('D, d M Y') ?>
    </div>
  </div>

  <!-- ── Stat Cards ── -->
  <div class="stat-grid">
    <div class="stat-card sc-blue anim d1">
      <div class="sc-icon"><i class="fas fa-briefcase"></i></div>
      <div class="sc-label">Total Brokers</div>
      <div class="sc-value" data-target="<?= (int)$totalBrokers ?>">0</div>
      <div class="sc-tag"><i class="fas fa-arrow-up"></i> Active Records</div>
    </div>
    <div class="stat-card sc-red anim d2">
      <div class="sc-icon"><i class="fas fa-ban"></i></div>
      <div class="sc-label">Blacklisted</div>
      <div class="sc-value" data-target="<?= (int)$totalBlacklisted ?>">0</div>
      <div class="sc-tag"><i class="fas fa-exclamation-triangle"></i> Flagged</div>
    </div>
    <div class="stat-card sc-green anim d3">
      <div class="sc-icon"><i class="fas fa-shield-alt"></i></div>
      <div class="sc-label">Regulators</div>
      <div class="sc-value" data-target="<?= (int)$totalRegulators ?>">0</div>
      <div class="sc-tag"><i class="fas fa-check"></i> Active Bodies</div>
    </div>
  </div>

  <!-- ── Main 2-col grid ── -->
  <div class="main-grid">

    <!-- Recent Brokers Table -->
    <div class="panel anim d4">
      <div class="panel-head">
        <div class="panel-title"><i class="fas fa-briefcase"></i> Recent Brokers</div>
        <span class="panel-pill">Latest 5</span>
      </div>
      <div style="overflow-x:auto;">
        <table class="data-table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Score</th>
              <th>Type</th>
              <th>Date Added</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($recentBrokers as $b): ?>
            <tr>
              <td><?= htmlspecialchars($b['name']) ?></td>
              <td><span class="td-score"><?= htmlspecialchars($b['score']) ?></span></td>
              <td><span class="td-type"><?= htmlspecialchars($b['broker_type']) ?></span></td>
              <td><span class="td-date"><?= date('d M Y', strtotime($b['created_at'])) ?></span></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Heatmap -->
    <div class="panel anim d5">
      <div class="panel-head">
        <div class="panel-title"><i class="fas fa-fire"></i> Performance Heatmap</div>
        <span class="panel-pill">Top 3</span>
      </div>
      <?php
        $hmCfg = [
          ['badge'=>'badge-trending','label'=>'Trending','bar'=>'bar-yellow','w'=>85],
          ['badge'=>'badge-gaining', 'label'=>'Gaining', 'bar'=>'bar-orange','w'=>58],
          ['badge'=>'badge-flagged', 'label'=>'Flagged', 'bar'=>'bar-red',   'w'=>35],
        ];
        foreach ($topBrokers as $i => $b):
          $c = $hmCfg[$i];
      ?>
      <div class="heatmap-item">
        <div class="hm-rank">#<?= $i+1 ?></div>
        <div>
          <div class="hm-name"><?= htmlspecialchars($b['name']) ?></div>
          <div class="hm-meta">
            <span class="hm-type"><?= htmlspecialchars($b['broker_type']) ?></span>
          </div>
          <div class="hm-bar">
            <div class="hm-bar-fill <?= $c['bar'] ?>" data-width="<?= $c['w'] ?>%"></div>
          </div>
        </div>
        <span class="hm-badge <?= $c['badge'] ?>"><?= $c['label'] ?></span>
      </div>
      <?php endforeach; ?>
    </div>

  </div><!-- /main-grid -->

  <!-- ── Blacklisted Table ── -->
  <div class="panel anim d5" style="margin-bottom:24px;">
    <div class="panel-head">
      <div class="panel-title">
        <i class="fas fa-ban" style="color:var(--red);"></i> Recent Blacklisted Brokers
      </div>
      <span class="panel-pill" style="color:var(--red);background:rgba(239,79,74,0.09);border-color:rgba(239,79,74,0.2);">
        ⚠ Flagged
      </span>
    </div>
    <div style="overflow-x:auto;">
      <table class="data-table">
        <thead>
          <tr>
            <th>Name</th>
            <th>Score</th>
            <th>Years in Business</th>
            <th>Date</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($recentBlacklisted as $b): ?>
          <tr>
            <td><?= htmlspecialchars($b['name']) ?></td>
            <td><span class="td-score danger"><?= htmlspecialchars($b['score']) ?></span></td>
            <td><?= htmlspecialchars($b['years_in_business']) ?> yrs</td>
            <td><span class="td-date"><?= date('d M Y', strtotime($b['created_at'])) ?></span></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- ── Charts ── -->
  <div class="charts-grid anim d6">

    <div class="panel">
      <div class="panel-head">
        <div class="panel-title"><i class="fas fa-chart-pie"></i> Regulation Status</div>
        <span class="panel-pill">Overview</span>
      </div>
      <div class="chart-body">
        <canvas id="pieChart" style="max-width:280px;max-height:220px;"></canvas>
      </div>
    </div>

    <div class="panel">
      <div class="panel-head">
        <div class="panel-title"><i class="fas fa-chart-bar"></i> Brokers by Country</div>
        <span class="panel-pill">Distribution</span>
      </div>
      <div class="chart-body" style="display:block;">
        <canvas id="barChart" style="max-height:210px;"></canvas>
      </div>
    </div>

  </div>

</main>

<!-- ══ Include Footer ══ -->
<?php include "includes/footer.php"; ?>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  // ── Animated counters
  document.querySelectorAll('.sc-value[data-target]').forEach(el => {
    const target = parseInt(el.dataset.target) || 0;
    if (target === 0) { el.textContent = '0'; return; }
    let current = 0;
    const step  = Math.max(1, Math.ceil(target / 45));
    const timer = setInterval(() => {
      current = Math.min(current + step, target);
      el.textContent = current;
      if (current >= target) clearInterval(timer);
    }, 28);
  });

  // ── Heatmap bar animation (after slight delay)
  setTimeout(() => {
    document.querySelectorAll('.hm-bar-fill').forEach(el => {
      el.style.width = el.dataset.width;
    });
  }, 350);

  // ── Chart defaults
  Chart.defaults.color = '#4a5068';
  Chart.defaults.font.family = "'JetBrains Mono', monospace";
  Chart.defaults.font.size = 10;

  // Donut chart
  new Chart(document.getElementById('pieChart'), {
    type: 'doughnut',
    data: {
      labels: ['Regulated', 'Unregulated', 'Blacklisted'],
      datasets: [{
        data: [70, 41, 17],
        backgroundColor: [
          'rgba(245,197,24,0.82)',
          'rgba(76,168,245,0.75)',
          'rgba(239,79,74,0.78)',
        ],
        borderColor: '#161a20',
        borderWidth: 3,
        hoverOffset: 8,
      }]
    },
    options: {
      responsive: true,
      cutout: '68%',
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            padding: 18,
            usePointStyle: true,
            pointStyleWidth: 9,
            color: '#8a90a6',
            font: { size: 11 },
          }
        }
      }
    }
  });

  // Bar chart
  new Chart(document.getElementById('barChart'), {
    type: 'bar',
    data: {
      labels: ['USA', 'UK', 'Australia', 'India', 'Others'],
      datasets: [{
        label: 'Brokers',
        data: [25, 40, 20, 15, 28],
        backgroundColor: [
          'rgba(245,197,24,0.75)',
          'rgba(245,197,24,0.60)',
          'rgba(245,197,24,0.48)',
          'rgba(245,197,24,0.36)',
          'rgba(245,197,24,0.24)',
        ],
        borderRadius: 8,
        borderSkipped: false,
      }]
    },
    options: {
      responsive: true,
      plugins: { legend: { display: false } },
      scales: {
        x: {
          grid: { color: 'rgba(255,255,255,0.03)' },
          ticks: { color: '#4a5068' },
        },
        y: {
          beginAtZero: true,
          grid: { color: 'rgba(255,255,255,0.04)' },
          ticks: { color: '#4a5068' },
        }
      }
    }
  });
</script>