<?php
session_start();
require_once __DIR__ . '/core/db_connect.php';

// ------------------------------
// AUTH CHECK
// ------------------------------
if (empty($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// ------------------------------
// ROLE CHECK (admin only)
// ------------------------------
$stmt = $conn_rbe->prepare('SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1');
$stmt->execute([(int)$_SESSION['user_id']]);
$role = $stmt->fetchColumn();

if ($role !== 'admin') {
    header('Location: login.php?error=unauthorized');
    exit;
}

// Safe to include navigation *after* successful auth
include 'admin-nav.php';
?>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>RBE Admin Dashboard</title>
  <link rel="stylesheet" href="/assets/css/theme.css">
  <link rel="stylesheet" href="/assets/css/admin.css">
</head>
<body>
<div class="wrap">
  <h1>Admin Dashboard</h1>

  <!-- System Health Bar -->
  <div id="healthBar" class="health-bar section-block">
    <div id="hDb" class="health-item" data-status="unknown"><span class="health-dot"></span> DB</div>
    <div id="hFlecto" class="health-item" data-status="unknown"><span class="health-dot"></span> Flecto API</div>
    <div id="hIammeter" class="health-item" data-status="unknown"><span class="health-dot"></span> IAMMETER API</div>
    <div id="hCron" class="health-item" data-status="unknown"><span class="health-dot"></span> Cron</div>
    <div id="hToken" class="health-item" data-status="unknown"><span class="health-dot"></span> Token</div>
    <div class="health-info">
      <span title="Green: OK (cron < 30 min). Yellow: Late (> 30 min). Red: Down (no cron logs or error).">Status legend</span>
    </div>
  </div>


  <!-- Live Insights -->
  <section id="insightsCards" class="cards insights section-block">
    <div class="card">
      <h4>Total kWh Today</h4>
      <div class="value accent" id="kwhToday">--</div>
      <small class="subtext">Real-time energy usage (IAMMETER + Flecto)</small>
    </div>

    <div class="card">
      <h4>Total kL Today</h4>
      <div class="value accent" id="klToday">--</div>
      <small class="subtext">Water consumption (All meters)</small>
    </div>

    <div class="card">
      <h4>Revenue Today</h4>
      <div class="value accent" id="revenueToday">--</div>
      <small class="subtext">Based on wallet deposits</small>
    </div>

    <div class="card clickable" onclick="scrollToAlerts()">
      <h4>Offline Meters</h4>
      <div id="offlineMeters" class="value">--</div>
    </div>
    <div class="card clickable" onclick="scrollToAlerts()">
      <h4>Active Alerts</h4>
      <div id="activeAlerts" class="value">--</div>
    </div>
  </section>


  <!-- Analytics Overview -->
  <section class="analytics-panel section-block">
    <header>
      <h3>Analytics Overview</h3>
      <div class="date-range">
        <input type="date" id="dateFrom" placeholder="From">
        <span>to</span>
        <input type="date" id="dateTo" placeholder="To">
        <button id="rangeApply">Apply</button>
      </div>
    </header>

    <div class="charts">
      <div class="chart-card">
        <h4>7-Day Energy vs Water</h4>
        <div class="mini-metrics">
          <span>Energy Today: <b id="chartEnergyToday">--</b></span>
          <span>Water Today: <b id="chartWaterToday">--</b></span>
        </div>
        <canvas id="chartEnergyWater" height="160"></canvas>
      </div>

      <div class="chart-card">
        <h4>30-Day Wallet Deposits vs Payouts</h4>
        <div class="mini-metrics">
          <span>Deposits: <b id="chartDepositsTotal">--</b></span>
          <span>Payouts: <b id="chartPayoutsTotal">--</b></span>
        </div>
        <canvas id="chartWallet" height="160"></canvas>
      </div>
    </div>
  </section>


  <!-- Finance Summary -->
  <section id="financeBox" class="finance section-block">
    <header onclick="this.parentElement.classList.toggle('open')">
      Finance Summary (click to expand)
      <span id="finNet">--</span>
    </header>
    <div class="content">
      <div class="cards">
        <div class="card"><h4>Total Deposits</h4><div id="finDeposits" class="value">--</div></div>
        <div class="card"><h4>Total Payouts</h4><div id="finPayouts" class="value">--</div></div>
      </div>
      <div style="margin:8px 0;">
        <button onclick="window.open('/core/db_functions.php?action=export_data&type=finance')">Export Finance CSV</button>
      </div>
      <h4 style="color:#7ed957; margin:12px 0 6px;">Top Landlords</h4>
      <ul id="topLandlords" class="muted"></ul>
    </div>
  </section>


  <!-- Alerts -->
  <section class="table-card alerts-section section-block">
    <h3 class="section-heading">Alerts &amp; System Warnings</h3>

    <!-- STATUS INFO -->
    <div style="margin-bottom:12px; padding:12px; background:#10202c; border-left:4px solid #00ccff;
                border-radius:6px; font-size:13px; line-height:1.45;">
      <strong style="color:#00ccff;">How to read these alerts:</strong>

      <div style="color:#ccc; margin-top:6px;">
        <div>[IAM] <strong>IAMMETER</strong> - No new readings for <strong>2+ hours</strong>.</div>
        <div>[FLE] <strong>FLECTO</strong> - No API updates for <strong>2+ hours</strong> (UTC + SAST corrected).</div>
        <div>[WTR] <strong>WATER</strong> - No water movement detected for <strong>2+ hours</strong>.</div>
        <div>[SYS] <strong>new</strong> - System auto-generated alert; clears automatically when meter syncs again.</div>
      </div>
    </div>

    <div style="margin-bottom:8px; display:flex; gap:10px;">
      <button onclick="window.open('/core/db_functions.php?action=export_data&type=alerts')">
        Export CSV
      </button>
      <span id="alertsCount" class="muted small"></span>
    </div>

    <table id="alertsTable" class="alerts">
      <thead>
        <tr>
          <th>Type</th>
          <th>Meter</th>
          <th>Property</th>
          <th>Last Sync</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody id="alertsBody">
        <tr><td colspan="5" class="muted">Loading...</td></tr>
      </tbody>
    </table>
  </section>


  <!-- Activity Feed -->
  <section class="activity section-block">
    <h3 class="section-heading">Activity</h3>
    <div style="margin-bottom:8px;">
      <button onclick="window.open('/core/db_functions.php?action=export_data&type=activity')">Export Activity CSV</button>
    </div>
    <ul id="activityFeed" class="activity-list"><li class="muted">Loading...</li></ul>
  </section>

  <!-- Tools Drawer -->
  <button id="toolsBtn" class="tools-btn">Tools</button>
  <div id="toolsDrawer" class="tools-drawer">
    <header>Admin Tools</header>
    <div class="content">
      <button data-action="manualSync">Manual Sync</button>
      <button data-action="clearCache">Clear Cache</button>
      <button data-action="viewTokens">View Tokens</button>
      <button data-action="viewCron">Cron Logs</button>
      <button data-action="refreshHealth">Refresh Health</button>
      <div class="muted tools-note">Tokens and Cron summaries shown in Health/Insights.</div>
    </div>
  </div>

  <!-- Optional legacy KPIs (totals) -->
  <section id="kpiCards" class="cards section-block">
    <div class="card"><h4>Total Meters</h4><div id="totalMeters" class="value">--</div></div>
    <div class="card"><h4>Active Tenants</h4><div id="activeTenants" class="value">--</div></div>
    <div class="card"><h4>Landlords</h4><div id="totalLandlords" class="value">--</div></div>
  </section>
</div>

<!-- Landlord Drill-down Modal -->
<div id="landlordModal" class="modal" role="dialog" aria-modal="true" aria-labelledby="landlordModalTitle">
  <div class="modal-content">
    <button class="close" aria-label="Close landlord details">&times;</button>
    <h3 id="landlordModalTitle" class="landlordName">Landlord</h3>
    <ul class="meterList"></ul>
    <p class="walletBalance"></p>
    <ul class="txList"></ul>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
<script src="/assets/js/admin.js"></script>

<script>
function scrollToAlerts() {
  const table = document.getElementById('alertsTable');
  if (table) {
    table.scrollIntoView({ behavior: 'smooth', block: 'center' });
    table.style.boxShadow = '0 0 20px rgba(0,204,255,0.6)';
    setTimeout(() => { table.style.boxShadow = 'none'; }, 1500);
  }
}
</script>

</body>
</html>
