<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();

// Stats
$totalUsers     = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE id > 1")->fetchColumn();
$activeUsers    = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE account_status='active'")->fetchColumn();
$totalTxns      = (int)$pdo->query("SELECT COUNT(*) FROM transactions")->fetchColumn();
$totalBalance   = (float)$pdo->query("SELECT COALESCE(SUM(account_balance),0) FROM users")->fetchColumn();
$totalDeposits  = (float)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE transaction_type='credit' AND status='completed'")->fetchColumn();
$totalWithdraws = (float)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE transaction_type IN('debit','transfer') AND status='completed'")->fetchColumn();
$pendingKyc     = (int)$pdo->query("SELECT COUNT(*) FROM kyc_documents WHERE status='pending'")->fetchColumn();
$openTickets    = (int)$pdo->query("SELECT COUNT(*) FROM support_tickets WHERE status='open'")->fetchColumn();
$pendingLoans   = (int)$pdo->query("SELECT COUNT(*) FROM loans WHERE status='pending'")->fetchColumn();
$activeInv      = (int)$pdo->query("SELECT COUNT(*) FROM investments WHERE status='active'")->fetchColumn();

// Recent transactions
$recentTxns = $pdo->query("SELECT t.*, CONCAT(u.first_name,' ',u.last_name) AS user_name FROM transactions t JOIN users u ON t.user_id=u.id ORDER BY t.created_at DESC LIMIT 10")->fetchAll();

// Recent users
$recentUsers = $pdo->query("SELECT * FROM users WHERE id > 1 ORDER BY created_at DESC LIMIT 8")->fetchAll();

// Chart data
$chartLabels = $chartCredits = $chartDebits = [];
for ($i = 5; $i >= 0; $i--) {
    $m = date('Y-m', strtotime("-$i months"));
    $chartLabels[]  = date('M Y', strtotime("-$i months"));
    $cr = (float)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE transaction_type='credit' AND status='completed' AND DATE_FORMAT(created_at,'%Y-%m')='$m'")->fetchColumn();
    $dr = (float)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE transaction_type IN('debit','transfer') AND status='completed' AND DATE_FORMAT(created_at,'%Y-%m')='$m'")->fetchColumn();
    $chartCredits[] = $cr; $chartDebits[] = $dr;
}

// New users per month
$newUsersChart = [];
for ($i = 5; $i >= 0; $i--) {
    $m = date('Y-m', strtotime("-$i months"));
    $newUsersChart[] = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE id > 1 AND DATE_FORMAT(created_at,'%Y-%m')='$m'")->fetchColumn();
}

$pageTitle = 'Dashboard';
?>
<?php include '../includes/header.php'; ?>
<div class="page-title d-flex justify-content-between align-items-center">
  <span><i class="fa fa-tachometer-alt me-2 text-danger"></i>Dashboard</span>
  <span class="text-muted small"><?= date('l, F j, Y') ?></span>
</div>

<!-- Stat Cards -->
<div class="row g-3 mb-4">
  <?php $stats = [
    ['Total Users',$totalUsers,'fa-users','red'],
    ['Active Users',$activeUsers,'fa-user-check','green'],
    ['Total Balance','$'.number_format($totalBalance,2),'fa-wallet','dark'],
    ['Total Transactions',$totalTxns,'fa-exchange-alt','blue'],
    ['Total Credited','$'.number_format($totalDeposits,2),'fa-arrow-down','green'],
    ['Total Debited','$'.number_format($totalWithdraws,2),'fa-arrow-up','red'],
    ['Pending KYC',$pendingKyc,'fa-id-card','gold'],
    ['Open Tickets',$openTickets,'fa-headset','purple'],
  ]; foreach ($stats as [$label,$val,$icon,$cls]): ?>
  <div class="col-6 col-md-3">
    <div class="stat-card <?= $cls ?>">
      <div class="d-flex justify-content-between align-items-start">
        <div><div class="label"><?= $label ?></div><div class="value"><?= $val ?></div></div>
        <div class="icon"><i class="fa <?= $icon ?>"></i></div>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Quick Actions -->
<div class="card mb-4">
  <div class="card-header">Quick Actions</div>
  <div class="card-body">
    <div class="row g-2">
      <?php $actions = [
        ['/admin/users.php?action=add','fa-user-plus','Add User','primary'],
        ['/admin/transactions.php?action=add','fa-plus-circle','Add Transaction','success'],
        ['/admin/kyc.php','fa-id-card','Review KYC','warning'],
        ['/admin/support.php','fa-headset','Support Tickets','danger'],
        ['/admin/loans.php','fa-hand-holding-usd','Manage Loans','info'],
        ['/admin/settings.php','fa-cog','Settings','secondary'],
      ]; foreach ($actions as [$href,$icon,$label,$cls]): ?>
      <div class="col-6 col-md-2">
        <a href="<?= $href ?>" class="btn btn-outline-<?= $cls ?> w-100 d-flex flex-column align-items-center py-2 gap-1">
          <i class="fa <?= $icon ?>"></i><small><?= $label ?></small>
        </a>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<!-- Charts -->
<div class="row g-4 mb-4">
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header">Transaction Volume (6 Months)</div>
      <div class="card-body"><canvas id="txnChart" height="120"></canvas></div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card">
      <div class="card-header">New Users (6 Months)</div>
      <div class="card-body"><canvas id="usersChart" height="120"></canvas></div>
    </div>
  </div>
</div>

<!-- Tables -->
<div class="row g-4">
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header d-flex justify-content-between"><span>Recent Transactions</span><a href="/admin/transactions.php" class="btn btn-sm btn-outline-primary">View All</a></div>
      <div class="table-responsive">
        <table class="table table-hover mb-0">
          <thead><tr><th>User</th><th>Type</th><th>Amount</th><th>Status</th><th>Date</th></tr></thead>
          <tbody>
          <?php foreach ($recentTxns as $t): $isC=$t['transaction_type']==='credit'; ?>
          <tr>
            <td class="small"><?= sanitize($t['user_name']) ?></td>
            <td><?= statusBadge($t['transaction_type']) ?></td>
            <td class="fw-bold <?= $isC?'text-success':'text-danger' ?>"><?= ($isC?'+':'-').money((float)$t['amount'],$t['currency']) ?></td>
            <td><?= statusBadge($t['status']) ?></td>
            <td class="small text-muted"><?= timeAgo($t['created_at']) ?></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <div class="col-lg-5">
    <div class="card">
      <div class="card-header d-flex justify-content-between"><span>New Users</span><a href="/admin/users.php" class="btn btn-sm btn-outline-primary">View All</a></div>
      <div class="table-responsive">
        <table class="table table-hover mb-0">
          <thead><tr><th>Name</th><th>Country</th><th>KYC</th><th>Joined</th></tr></thead>
          <tbody>
          <?php foreach ($recentUsers as $u): ?>
          <tr>
            <td class="small fw-bold"><?= sanitize($u['first_name'].' '.$u['last_name']) ?></td>
            <td class="small"><?= sanitize($u['country']??'—') ?></td>
            <td><?= statusBadge($u['kyc_status']) ?></td>
            <td class="small text-muted"><?= timeAgo($u['created_at']) ?></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<?php include '../includes/footer.php'; ?>
<script>
const labels = <?= json_encode($chartLabels) ?>;
new Chart(document.getElementById('txnChart'), {
  type: 'bar',
  data: { labels, datasets: [
    {label:'Credits',data:<?= json_encode($chartCredits) ?>,backgroundColor:'rgba(26,188,156,.75)',borderRadius:5},
    {label:'Debits',data:<?= json_encode($chartDebits) ?>,backgroundColor:'rgba(192,57,43,.75)',borderRadius:5},
  ]},
  options:{responsive:true,maintainAspectRatio:true,plugins:{legend:{position:'top'}},scales:{y:{ticks:{callback:v=>'$'+Number(v).toLocaleString()}}}}
});
new Chart(document.getElementById('usersChart'), {
  type: 'line',
  data: { labels, datasets: [{label:'New Users',data:<?= json_encode($newUsersChart) ?>,borderColor:'#c0392b',backgroundColor:'rgba(192,57,43,.1)',fill:true,tension:0.4,borderWidth:2}]},
  options:{responsive:true,maintainAspectRatio:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{stepSize:1}}}}
});
</script>
