<?php
session_start();
if (!isset($_SESSION['admin'])) { header("Location: ../logout"); exit; }
require_once '../core/conn.php';
date_default_timezone_set('Africa/Lagos');

function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

function table_exists(mysqli $con, string $table): bool {
  $dbRes = $con->query("SELECT DATABASE() AS db");
  $dbRow = $dbRes ? $dbRes->fetch_assoc() : null;
  $db = $dbRow['db'] ?? '';
  if (!$db) return false;

  $stmt = $con->prepare("SELECT COUNT(*) AS c FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME=?");
  $stmt->bind_param("ss", $db, $table);
  $stmt->execute();
  $row = $stmt->get_result()->fetch_assoc();
  $stmt->close();
  return ((int)($row['c'] ?? 0)) > 0;
}

function sum_payments(mysqli $con, string $method): float {
  $stmt = $con->prepare("SELECT COALESCE(SUM(amount),0) AS total FROM payments WHERE status=1 AND method=?");
  $stmt->bind_param("s", $method);
  $stmt->execute();
  $row = $stmt->get_result()->fetch_assoc();
  $stmt->close();
  return (float)($row['total'] ?? 0);
}

/* ===== Admin ===== */
$admin = null;
$stmt = $con->prepare("SELECT id, username, status FROM admin WHERE id=? LIMIT 1");
$stmt->bind_param("i", $_SESSION['admin']);
$stmt->execute();
$admin = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$admin) { session_destroy(); header("Location: ../logout"); exit; }

/* ===== Staff stats (users table) ===== */
$staffTotal = 0; $staffActive = 0; $staffBanned = 0;

$q = $con->query("SELECT COUNT(*) AS total FROM users WHERE type LIKE '%STAFF%'");
if ($q) $staffTotal = (int)($q->fetch_assoc()['total'] ?? 0);

$q = $con->query("SELECT COUNT(*) AS total FROM users WHERE type LIKE '%STAFF%' AND status=1");
if ($q) $staffActive = (int)($q->fetch_assoc()['total'] ?? 0);

$q = $con->query("SELECT COUNT(*) AS total FROM users WHERE type LIKE '%STAFF%' AND status=2");
if ($q) $staffBanned = (int)($q->fetch_assoc()['total'] ?? 0);

/* ===== Branches ===== */
$branches = [];
$hasBranches = table_exists($con, 'branches');
if ($hasBranches) {
  $qb = $con->query("SELECT id, company_name, state, lga, status FROM branches WHERE status=1 ORDER BY id DESC");
  if ($qb) while ($b = $qb->fetch_assoc()) $branches[] = $b;
}

/* ===== Payments totals ===== */
$hasPayments = table_exists($con, 'payments');
$posTotal  = $hasPayments ? sum_payments($con, 'POS') : 0.00;
$cashTotal = $hasPayments ? sum_payments($con, 'CASH') : 0.00;
$bankTotal = $hasPayments ? sum_payments($con, 'BANK_TRANSFER') : 0.00;

/* ===== Transactions (optional) ===== */
$tx = [];
$hasTransactions = table_exists($con, 'transactions');
if ($hasTransactions) {
  $qtx = $con->query("SELECT * FROM transactions ORDER BY id DESC LIMIT 20");
  if ($qtx) while ($t = $qtx->fetch_assoc()) $tx[] = $t;
}

/* ===== Header + Navigation (your new responsive header.php) ===== */
$active = 'dashboard';
include 'include/header.php';
?>
<div class="page-title">
  <div>
    <h2>Dashboard Overview</h2>
    <p>Today: <b><?php echo date('l, d M Y'); ?></b> • Time: <b><?php echo date('H:i'); ?></b></p>
  </div>

  
</div>
<div class="hero">
  <div class="hero-inner">
    <div style="font-weight:1200; color:#0b2a66;">
      Welcome back, <?php echo h($admin['username']); ?> 👋
      <div style="margin-top:6px; color:#64748b; font-size:12px; font-weight:900;">
        Staff + Payments + Branches summary in one view.
      </div>
    </div>

    <div class="chips">
      <div class="chip">Staff: <?php echo number_format($staffTotal); ?></div>
      <div class="chip">Active Branches: <?php echo number_format(count($branches)); ?></div>
      <div class="chip">Payments: <?php echo $hasPayments ? "Enabled" : "Missing table"; ?></div>
    </div>
  </div>
</div>

<section class="grid">
  <div class="card span4">
    <div class="body">
      <div class="stat">
        <div class="icon">👥</div>
        <div>
          <p class="k">Total Staffs</p>
          <div class="v"><?php echo number_format($staffTotal); ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="card span4">
    <div class="body">
      <div class="stat">
        <div class="icon good">✅</div>
        <div>
          <p class="k">Active Staffs</p>
          <div class="v"><?php echo number_format($staffActive); ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="card span4">
    <div class="body">
      <div class="stat">
        <div class="icon bad">⛔</div>
        <div>
          <p class="k">Banned Staffs</p>
          <div class="v"><?php echo number_format($staffBanned); ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="card span4">
    <div class="body">
      <div class="stat">
        <div class="icon">💳</div>
        <div>
          <p class="k">Approved POS Amount</p>
          <div class="v">₦ <?php echo number_format($posTotal, 2); ?></div>
          <?php if(!$hasPayments): ?><div style="color:#64748b; font-size:12px; margin-top:6px;">payments table not found</div><?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <div class="card span4">
    <div class="body">
      <div class="stat">
        <div class="icon warn">💵</div>
        <div>
          <p class="k">Approved Cash Amount</p>
          <div class="v">₦ <?php echo number_format($cashTotal, 2); ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="card span4">
    <div class="body">
      <div class="stat">
        <div class="icon">🏦</div>
        <div>
          <p class="k">Approved Bank Transfer</p>
          <div class="v">₦ <?php echo number_format($bankTotal, 2); ?></div>
        </div>
      </div>
    </div>
  </div>
</section>

<section class="grid">
  <div class="card span12">
    <div class="head">
      <h3>Active Branches</h3>
      <div class="tools">
        <input class="inp" id="branchSearch" placeholder="Search branch, state, lga...">
        <a class="btnx primary" href="branches-active.php">View All</a>
      </div>
    </div>
    <div class="body">
      <?php if(!$hasBranches): ?>
        <div class="note">branches table not found.</div>
      <?php elseif(empty($branches)): ?>
        <div class="note">No active branches found (status=1).</div>
      <?php else: ?>
        <div class="tablewrap">
          <table id="branchesTable">
            <thead>
              <tr>
                <th>#</th>
                <th>Company Name</th>
                <th>State</th>
                <th>LGA</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
            <?php $i=1; foreach($branches as $b): ?>
              <tr>
                <td><?php echo $i++; ?></td>
                <td><?php echo h($b['company_name']); ?></td>
                <td><?php echo h($b['state']); ?></td>
                <td><?php echo h($b['lga']); ?></td>
                <td><span class="badge b-ok">ACTIVE</span></td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
</section>

<section class="grid">
  <div class="card span12">
    <div class="head">
      <h3>Latest 20 Transactions</h3>
      <div class="tools">
        <input class="inp" id="txSearch" placeholder="Search username, transid, service...">
      </div>
    </div>
    <div class="body">
      <?php if(!$hasTransactions): ?>
        <div class="note">transactions table not found. Create it or change dashboard to your real table name.</div>
      <?php elseif(empty($tx)): ?>
        <div class="note">No transactions found.</div>
      <?php else: ?>
        <div class="tablewrap">
          <table id="txTable">
            <thead>
              <tr>
                <th>#</th>
                <th>Username</th>
                <th>Trans ID</th>
                <th>Service</th>
                <th>Mobile</th>
                <th>Amount</th>
                <th>Date</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
            <?php $n=1; foreach($tx as $t): ?>
              <?php
                $st = (int)($t['status'] ?? 0);
                $badge = $st===1 ? "<span class='badge b-ok'>APPROVED</span>" : ($st===2 ? "<span class='badge b-warn'>CANCELLED</span>" : "<span class='badge b-bad'>FAILED</span>");
              ?>
              <tr>
                <td><?php echo $n++; ?></td>
                <td><?php echo h($t['username'] ?? ''); ?></td>
                <td><?php echo h($t['transid'] ?? ($t['transref'] ?? '')); ?></td>
                <td><?php echo h($t['service'] ?? ($t['servicename'] ?? '')); ?></td>
                <td><?php echo h($t['mobile'] ?? ($t['phone'] ?? '')); ?></td>
                <td><?php echo "₦ ".number_format((float)($t['amount'] ?? 0), 2); ?></td>
                <td><?php echo h($t['date'] ?? ''); ?></td>
                <td><?php echo $badge; ?></td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
</section>

<div style="margin-top:14px; color:#64748b; font-size:12px; font-weight:900;">
  © <?php echo date('Y'); ?> Gas Admin
</div>

<script>
  function bindSearch(inputId, tableId){
    const input = document.getElementById(inputId);
    const table = document.getElementById(tableId);
    if(!input || !table) return;
    input.addEventListener('input', () => {
      const q = input.value.toLowerCase().trim();
      table.querySelectorAll('tbody tr').forEach(tr => {
        tr.style.display = tr.innerText.toLowerCase().includes(q) ? '' : 'none';
      });
    });
  }
  bindSearch('branchSearch','branchesTable');
  bindSearch('txSearch','txTable');
</script>


</div><!-- .main -->
</div><!-- .layout -->
