<?php
require_once __DIR__ . '/auth.php';
require 'config.php'; // defines $pdo

// Only include non-deleted transactions
$deletedFilter = "deleted_at IS NULL";

/* =========================
   TOTAL AMOUNT RECEIVED
========================= */
$totalReceived = $pdo->query("
    SELECT COALESCE(SUM(amount), 0)
    FROM mpesa_payments
    WHERE status = 'paid' AND $deletedFilter
")->fetchColumn();

/* =========================
   TOTAL AMOUNT FAILED
========================= */
$totalFailed = $pdo->query("
    SELECT COALESCE(SUM(amount), 0)
    FROM mpesa_payments
    WHERE status = 'failed' AND $deletedFilter
")->fetchColumn();

/* =========================
   ENTITY TOTALS (SUCCESS)
========================= */
$successByEntity = $pdo->query("
    SELECT entity, SUM(amount) AS total
    FROM mpesa_payments
    WHERE status = 'paid' AND $deletedFilter
    GROUP BY entity
    ORDER BY total DESC
")->fetchAll(PDO::FETCH_ASSOC);

/* =========================
   ENTITY TOTALS (FAILED)
========================= */
$failedByEntity = $pdo->query("
    SELECT entity, SUM(amount) AS total
    FROM mpesa_payments
    WHERE status = 'failed' AND $deletedFilter
    GROUP BY entity
    ORDER BY total DESC
")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swingtide Admin Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/x-icon" href="icon.png">

<style>
:root{
  --bg:#f5f7fb;
  --card:#ffffff;
  --primary:#2563eb;
  --success:#16a34a;
  --danger:#dc2626;
  --text:#0f172a;
  --muted:#64748b;
  --border:#e5e7eb;
  --radius:16px;
}

*{box-sizing:border-box}

body{
  margin:0;
  font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;
  background:var(--bg);
  color:var(--text);
}

/* Layout */
.dashboard{
  display:grid;
  grid-template-columns:260px 1fr;
  min-height:100vh;
}

/* Sidebar */
.sidebar{
  background:#0f172a;
  color:#e5e7eb;
  padding:24px;
}

.brand{
  font-size:1.3rem;
  font-weight:700;
  margin-bottom:32px;
}

.nav a{
  display:block;
  padding:12px 14px;
  border-radius:10px;
  color:#e5e7eb;
  text-decoration:none;
  margin-bottom:8px;
}

.nav a:hover{background:rgba(255,255,255,.08)}
.nav a.active{background:var(--primary)}

/* Main */
.main{padding:32px}

/* Topbar */
.topbar{
  display:flex;
  justify-content:space-between;
  align-items:center;
  margin-bottom:32px;
}

.topbar h1{margin:0;font-size:1.8rem}

/* Cards */
.cards{
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
  gap:24px;
  margin-bottom:32px;
}

.card{
  background:var(--card);
  border-radius:var(--radius);
  padding:24px;
  box-shadow:0 20px 40px rgba(0,0,0,.06);
}

.card h3{
  margin:0 0 8px;
  font-size:.9rem;
  color:var(--muted);
}

.card .value{
  font-size:2rem;
  font-weight:700;
}

/* Panels */
.panel{
  background:var(--card);
  border-radius:var(--radius);
  padding:24px;
  box-shadow:0 20px 40px rgba(0,0,0,.06);
  margin-bottom:32px;
}

table{
  width:100%;
  border-collapse:collapse;
}

td{
  padding:10px 6px;
  border-bottom:1px solid var(--border);
}

.amount{text-align:right;font-weight:600}

.success{color:var(--success)}
.failed{color:var(--danger)}

.footer{
  color:var(--muted);
  font-size:.85rem;
}
</style>
</head>

<body>

<div class="dashboard">

  <!-- Sidebar -->
  <aside class="sidebar">
    <div class="brand">Swingtide Admin</div>
    <nav class="nav">
      <a class="active" href="index.php">Dashboard</a>
      <a href="transactions.php" target="_blank">Transactions</a>
      <a href="search_receipt.php" target="_blank">Search Receipts</a>
      <a href="manage.php" target="_blank">Manage Transactions</a>
      <a href="change_password.php" target="_blank">Change Password</a>
      <a href="logout.php">Logout</a>
    </nav>
  </aside>

  <!-- Main -->
  <main class="main">

    <div class="topbar">
      <h1>Dashboard</h1>
      <div>
        Logged in as <strong><?= htmlspecialchars($_SESSION['admin_user'] ?? '') ?></strong>
      </div>
    </div>

    <!-- KPI Cards -->
    <section class="cards">
      <div class="card">
        <h3>Total Amount Received</h3>
        <div class="value success">
          KES <?= number_format($totalReceived, 2) ?>
        </div>
      </div>

      <div class="card">
        <h3>Total Amount Failed</h3>
        <div class="value failed">
          KES <?= number_format($totalFailed, 2) ?>  
      </div>
      </div>
    </section>

    <!-- Entity Breakdown -->
    <section class="panel">
      <h2>Entity Transaction Breakdown</h2>

      <div style="display:grid;grid-template-columns:1fr 1fr;gap:32px">

        <!-- Success -->
        <div>
          <h3 class="success">Successful Transactions</h3>
          <table>
            <?php foreach ($successByEntity as $row): ?>
              <tr>
                <td><?= htmlspecialchars($row['entity'] ?: 'Unknown') ?></td>
                <td class="amount success">
                  KES <?= number_format($row['total'], 2) ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </table>
        </div>

        <!-- Failed -->
        <div>
          <h3 class="failed">Failed Transactions</h3>
          <table>
            <?php foreach ($failedByEntity as $row): ?>
              <tr>
                <td><?= htmlspecialchars($row['entity'] ?: 'Unknown') ?></td>
                <td class="amount failed">
                  KES <?= number_format($row['total'], 2) ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </table>
        </div>

      </div>
    </section>

    <div class="footer">
      &copy; <?= date('Y') ?> Swingtide. All rights reserved.
    </div>

  </main>

</div>

</body>
</html>
