<?php
/* agent-dashboard.php */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'db_connect.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php"); exit();
}
$user_id = (int)$_SESSION['user_id'];

/* ----------------------------
   Role gate: Admin OR Agent
----------------------------- */
$roleStmt = $conn_rbe->prepare("
  SELECT 1 
  FROM rbe_roles 
  WHERE user_id = ? AND role IN ('admin','agent') 
  LIMIT 1
");
$roleStmt->execute([$user_id]);
$allowed = (bool)$roleStmt->fetchColumn();
if (!$allowed) { echo "Access denied. Admins and Agents only."; exit(); }

/* ----------------------------
   Helpers
----------------------------- */
function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

// Detect current DB for INFORMATION_SCHEMA checks
$dbName = $conn_rbe->query("SELECT DATABASE()")->fetchColumn();

/** Check if a column exists in a table (for optional agent scoping) */
function columnExists(PDO $pdo, string $db, string $table, string $col): bool {
    $q = $pdo->prepare("
      SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1
    ");
    $q->execute([$db, $table, $col]);
    return (bool)$q->fetchColumn();
}

// Is user an Agent?
$isAgentStmt = $conn_rbe->prepare("
  SELECT 1 FROM rbe_roles WHERE user_id = ? AND role = 'agent' LIMIT 1
");
$isAgentStmt->execute([$user_id]);
$isAgent = (bool)$isAgentStmt->fetchColumn();

// Optional agent_id columns?
$hasAgentSmart   = columnExists($conn_rbe, $dbName, 'smart_meters', 'agent_id');
$hasAgentFlecto  = columnExists($conn_rbe, $dbName, 'flecto_meters', 'agent_id');
$hasAgentWater   = columnExists($conn_rbe, $dbName, 'water_meters',  'agent_id');
$hasAgentProps   = columnExists($conn_rbe, $dbName, 'properties',    'agent_id');

// For scoping, simplest convention: agent_id == the agent's rbe_users.id (user_id)
$agent_id = $user_id;

/* ----------------------------
   Handle POST: Add meters
----------------------------- */

// Add IAMMETER
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_meter'])) {
    $serial      = trim($_POST['meter_serial'] ?? '');
    $phases      = (int)($_POST['phases'] ?? 0);
    $property_id = (int)($_POST['property_id'] ?? 0);
    $landlord_id = (int)($_POST['landlord_id'] ?? 0);
    $tenant_id   = (int)($_POST['tenant_id'] ?? 0);

    if ($serial && $phases && $property_id && $landlord_id && $tenant_id) {
        if ($hasAgentSmart) {
            $stmt = $conn_rbe->prepare("
              INSERT INTO smart_meters
                (serial, phases, property_id, landlord_id, tenant_id, source_type, meter_type, agent_id)
              VALUES
                (?, ?, ?, ?, ?, 'IAMMETER', 'electricity', ?)
            ");
            $stmt->execute([$serial, $phases, $property_id, $landlord_id, $tenant_id, $agent_id]);
        } else {
            $stmt = $conn_rbe->prepare("
              INSERT INTO smart_meters
                (serial, phases, property_id, landlord_id, tenant_id, source_type, meter_type)
              VALUES
                (?, ?, ?, ?, ?, 'IAMMETER', 'electricity')
            ");
            $stmt->execute([$serial, $phases, $property_id, $landlord_id, $tenant_id]);
        }
        $flash_msg = "✅ IAMMETER meter added!";
    } else {
        $flash_err = "❌ Please fill all fields.";
    }
}

// Add FLECTO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_flecto_meter'])) {
    $serial      = trim($_POST['serial_number'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $property_id = (int)($_POST['property_id'] ?? 0);
    $landlord_id = (int)($_POST['landlord_id'] ?? 0);
    $tenant_id   = (int)($_POST['tenant_id'] ?? 0);

    if ($serial && $description && $property_id && $landlord_id && $tenant_id) {
        if ($hasAgentFlecto) {
            $stmt = $conn_rbe->prepare("
              INSERT INTO flecto_meters
                (serial_number, description, property_id, landlord_id, tenant_id, is_active, agent_id)
              VALUES
                (?, ?, ?, ?, ?, 1, ?)
            ");
            $stmt->execute([$serial, $description, $property_id, $landlord_id, $tenant_id, $agent_id]);
        } else {
            $stmt = $conn_rbe->prepare("
              INSERT INTO flecto_meters
                (serial_number, description, property_id, landlord_id, tenant_id, is_active)
              VALUES
                (?, ?, ?, ?, ?, 1)
            ");
            $stmt->execute([$serial, $description, $property_id, $landlord_id, $tenant_id]);
        }
        $flash_msg = "✅ FLECTO meter added!";
    } else {
        $flash_err = "❌ Please fill all fields.";
    }
}

/* ----------------------------
   Quick stats (scoped when possible)
----------------------------- */

// Properties count
if ($isAgent && $hasAgentProps) {
    $pStmt = $conn_rbe->prepare("SELECT COUNT(*) FROM properties WHERE agent_id = :aid");
    $pStmt->execute([':aid' => $agent_id]);
    $propertiesCount = (int)$pStmt->fetchColumn();
} else {
    $propertiesCount = (int)$conn_rbe->query("SELECT COUNT(*) FROM properties")->fetchColumn();
}

// Landlords count (landlords who own properties for this agent)
if ($isAgent && $hasAgentProps) {
    $landlordsStmt = $conn_rbe->prepare("
      SELECT COUNT(DISTINCT p.landlord_id)
      FROM properties p
      WHERE p.agent_id = :aid
    ");
    $landlordsStmt->execute([':aid' => $agent_id]);
    $landlordsCount = (int)$landlordsStmt->fetchColumn();
} else {
    $landlordsCount = (int)$conn_rbe->query("SELECT COUNT(*) FROM rbe_roles WHERE role='landlord'")->fetchColumn();
}

// Tenants count (scoped via meters; use unique placeholders across UNION)
if ($isAgent && ($hasAgentSmart || $hasAgentFlecto || $hasAgentWater)) {
    $parts  = [];
    $params = [];
    $i = 0;

    if ($hasAgentSmart)  { $i++; $parts[] = "SELECT tenant_id FROM smart_meters  WHERE agent_id = :aid{$i} AND tenant_id IS NOT NULL";  $params[":aid{$i}"] = $agent_id; }
    if ($hasAgentFlecto) { $i++; $parts[] = "SELECT tenant_id FROM flecto_meters WHERE agent_id = :aid{$i} AND tenant_id IS NOT NULL";  $params[":aid{$i}"] = $agent_id; }
    if ($hasAgentWater)  { $i++; $parts[] = "SELECT tenant_id FROM water_meters  WHERE agent_id = :aid{$i} AND tenant_id IS NOT NULL";  $params[":aid{$i}"] = $agent_id; }

    if ($parts) {
        $sub = implode(" UNION ", $parts);
        $tenantsStmt = $conn_rbe->prepare("
          SELECT COUNT(DISTINCT t.id)
          FROM rbe_users t
          JOIN rbe_roles rr ON rr.user_id = t.id AND rr.role='tenant'
          WHERE t.id IN ($sub)
        ");
        $tenantsStmt->execute($params);
        $tenantsCount = (int)$tenantsStmt->fetchColumn();
    } else {
        $tenantsCount = (int)$conn_rbe->query("SELECT COUNT(*) FROM rbe_roles WHERE role='tenant'")->fetchColumn();
    }
} else {
    $tenantsCount = (int)$conn_rbe->query("SELECT COUNT(*) FROM rbe_roles WHERE role='tenant'")->fetchColumn();
}

// Meter counts (scoped when possible)
if ($isAgent && $hasAgentSmart) {
    $sCount = $conn_rbe->prepare("SELECT COUNT(*) FROM smart_meters WHERE agent_id = ?");
    $sCount->execute([$agent_id]); $iammetersCount = (int)$sCount->fetchColumn();
} else {
    $iammetersCount = (int)$conn_rbe->query("SELECT COUNT(*) FROM smart_meters")->fetchColumn();
}
if ($isAgent && $hasAgentFlecto) {
    $fCount = $conn_rbe->prepare("SELECT COUNT(*) FROM flecto_meters WHERE agent_id = ?");
    $fCount->execute([$agent_id]); $flectoCount = (int)$fCount->fetchColumn();
} else {
    $flectoCount = (int)$conn_rbe->query("SELECT COUNT(*) FROM flecto_meters")->fetchColumn();
}
if ($isAgent && $hasAgentWater) {
    $wCount = $conn_rbe->prepare("SELECT COUNT(*) FROM water_meters WHERE agent_id = ?");
    $wCount->execute([$agent_id]); $waterCount = (int)$wCount->fetchColumn();
} else {
    $waterCount = (int)$conn_rbe->query("SELECT COUNT(*) FROM water_meters")->fetchColumn();
}
$totalMeters = $iammetersCount + $flectoCount + $waterCount;

/* ----------------------------
   Pagination helpers
----------------------------- */
function positiveInt($v, $def=1){ $n = (int)$v; return $n>0?$n:$def; }
$limit = 5;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>RBE Agent Dashboard</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body{font-family:Arial, sans-serif;background:#051a25;color:#fff;margin:0;padding:20px}
  header{text-align:center;margin-bottom:30px}
  img.logo{width:200px;margin-bottom:10px}
  h1{color:#7ed957;font-size:2.2em;margin-bottom:20px}
  .nav{display:flex;flex-wrap:wrap;justify-content:center;gap:15px;margin:0 auto 30px;max-width:1000px}
  .nav a{background:#7ed957;color:#000;padding:15px 25px;border-radius:12px;text-decoration:none;font-weight:bold;text-align:center;flex:1 1 160px;box-shadow:0 3px 8px rgba(0,0,0,.4);transition:background .3s, transform .2s}
  .nav a:hover{background:#00cc77;transform:translateY(-2px)}
  .section{background:#122c4c;padding:25px;margin:20px auto;border-radius:15px;max-width:1000px;box-shadow:0 6px 20px rgba(0,0,0,.6)}
  .section h2,.section h3{color:#7ed957;margin-top:0}
  .quick-stats{display:flex;flex-wrap:wrap;justify-content:center;gap:20px;margin-top:20px}
  .stat-card{background:#1b3a4d;padding:20px;border-radius:12px;min-width:140px;text-align:center;box-shadow:0 4px 12px rgba(0,0,0,.4);flex:1 1 150px;transition:transform .3s}
  .stat-card:hover{transform:scale(1.05)}
  .stat-card h4{margin:5px 0;font-size:1.1em;color:#7ed957}
  .stat-card p{margin:0;font-size:1.4em;font-weight:bold}
  .stat-card1{background:#7ed957;padding:20px;border-radius:12px;min-width:140px;text-align:center;box-shadow:0 4px 12px rgba(0,0,0,.4);flex:1 1 150px;transition:transform .3s}
  .stat-card1:hover{transform:scale(1.05)}
  .stat-card1 h4{margin:5px 0;font-size:1.1em;color:#1b3a4d}
  .stat-card1 p{margin:0;font-size:1.4em;font-weight:bold;color:#0b1a24}
  @media (max-width:480px){.nav a{flex:1 1 90%}.section,.stat-card{width:90%}}
  table{width:100%;background:#1b3a4d;color:#fff;border-collapse:collapse;border-radius:8px;overflow:hidden}
  table tr:hover{background:#1f4860}
  table td,table th{text-align:center;border:none;font-size:.95em;padding:12px}
  table th{font-weight:bold;color:#7ed957;background:#0f2536}
  a{color:#66b3ff;text-decoration:none}
  a:hover{text-decoration:underline;color:#00ccff}
  .flash{margin:10px 0;padding:10px 14px;border-radius:8px}
  .ok{background:#0f3b2a;color:#b6ffcf;border:1px solid #176546}
  .err{background:#3b0f0f;color:#ffd6d6;border:1px solid #6b1a1a}
  .divider{margin:40px 0;border-color:#2e4e65}
</style>
</head>
<body>
  <header>
    <img src="https://rbelectrical.enterprises/wp-content/uploads/2024/07/RBE-Electrical-Logo-clear2-250x125.png" alt="RBE Logo" class="logo">
    <h1><?= $isAgent ? 'RBE Agent Dashboard' : 'RBE Agent Dashboard' ?></h1>
  </header>

  <div class="nav">
    <a href="manage-landlords.php">Manage Landlords</a>
    <a href="properties.php">Manage Properties</a>
    <a href="manage-tenants.php">Manage Tenants</a>
    <a href="admin-reports.php">Reports</a>
    <a href="logout.php">Logout</a>
  </div>

  <div class="section">
    <?php if (!empty($flash_msg)): ?>
      <div class="flash ok"><?= esc($flash_msg) ?></div>
    <?php endif; ?>
    <?php if (!empty($flash_err)): ?>
      <div class="flash err"><?= esc($flash_err) ?></div>
    <?php endif; ?>

    <h2>Quick Stats</h2>
    <div class="quick-stats">
      <div class="stat-card"><h4>Landlords</h4><p><?= (int)$landlordsCount ?></p></div>
      <div class="stat-card"><h4>Tenants</h4><p><?= (int)$tenantsCount ?></p></div>
      <div class="stat-card"><h4>Properties</h4><p><?= (int)$propertiesCount ?></p></div>
      <div class="stat-card"><h4>IAMMETER Meters</h4><p><?= (int)$iammetersCount ?></p></div>
      <div class="stat-card"><h4>FLECTO Meters</h4><p><?= (int)$flectoCount ?></p></div>
      <div class="stat-card"><h4>Water Meters</h4><p><?= (int)$waterCount ?></p></div>
      <div class="stat-card1"><h4>Total Meters</h4><p><?= (int)$totalMeters ?></p></div>
    </div>
  </div>

  <div class="section">
    <h2 style="color:#7ed957;">Meter Management</h2>

    <!-- IAMMETER Meter Form -->
    <h3>Add IAMMETER Meter</h3>
    <form method="post" action="">
      <input type="text"   name="meter_serial" placeholder="Meter Serial" required>
      <input type="number" name="phases"       placeholder="Phases (1 or 3)" required>

      <select name="property_id" required>
        <option value="">Assign to Property</option>
        <?php
        if ($isAgent && $hasAgentProps) {
          $stmt = $conn_rbe->prepare("SELECT id, property_number FROM properties WHERE agent_id = :aid ORDER BY property_number ASC");
          $stmt->execute([':aid'=>$agent_id]);
        } else {
          $stmt = $conn_rbe->query("SELECT id, property_number FROM properties ORDER BY property_number ASC");
        }
        while ($prop = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo "<option value='".(int)$prop['id']."'>".esc($prop['property_number'])."</option>";
        }
        ?>
      </select>

      <select name="landlord_id" required>
        <option value="">Assign to Landlord</option>
        <?php
        // If scoping by properties, pre-filter landlords who own those properties
        if ($isAgent && $hasAgentProps) {
          $stmt = $conn_rbe->prepare("
            SELECT DISTINCT u.id, u.fullname
            FROM rbe_users u
            JOIN rbe_roles r ON r.user_id = u.id AND r.role='landlord'
            JOIN properties p ON p.landlord_id = u.id
            WHERE p.agent_id = :aid
            ORDER BY u.fullname ASC
          ");
          $stmt->execute([':aid'=>$agent_id]);
        } else {
          $stmt = $conn_rbe->query("
            SELECT u.id, u.fullname
            FROM rbe_users u
            JOIN rbe_roles r ON u.id = r.user_id AND r.role='landlord'
            ORDER BY u.fullname ASC
          ");
        }
        while ($ll = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo "<option value='".(int)$ll['id']."'>".esc($ll['fullname'])."</option>";
        }
        ?>
      </select>

      <select name="tenant_id" required>
  <option value="">Assign to Tenant</option>
  <?php
  if ($isAgent && ($hasAgentSmart || $hasAgentFlecto || $hasAgentWater)) {
      $parts  = [];
      $params = [];
      $i = 0;

      if ($hasAgentSmart)  { $i++; $parts[] = "SELECT tenant_id FROM smart_meters  WHERE agent_id = :aid{$i}"; $params[":aid{$i}"] = $agent_id; }
      if ($hasAgentFlecto) { $i++; $parts[] = "SELECT tenant_id FROM flecto_meters WHERE agent_id = :aid{$i}"; $params[":aid{$i}"] = $agent_id; }
      if ($hasAgentWater)  { $i++; $parts[] = "SELECT tenant_id FROM water_meters  WHERE agent_id = :aid{$i}"; $params[":aid{$i}"] = $agent_id; }

      if ($parts) {
          $sub = implode(" UNION ", $parts);
          $stmt = $conn_rbe->prepare("
            SELECT DISTINCT u.id, u.fullname
            FROM rbe_users u
            JOIN rbe_roles r ON r.user_id = u.id AND r.role='tenant'
            WHERE u.id IN ($sub)
            ORDER BY u.fullname ASC
          ");
          $stmt->execute($params);
      } else {
          $stmt = $conn_rbe->query("
            SELECT u.id, u.fullname
            FROM rbe_users u
            JOIN rbe_roles r ON u.id = r.user_id AND r.role='tenant'
            ORDER BY u.fullname ASC
          ");
      }
  } else {
      $stmt = $conn_rbe->query("
        SELECT u.id, u.fullname
        FROM rbe_users u
        JOIN rbe_roles r ON u.id = r.user_id AND r.role='tenant'
        ORDER BY u.fullname ASC
      ");
  }
  while ($t = $stmt->fetch(PDO::FETCH_ASSOC)) {
      echo "<option value='".(int)$t['id']."'>".esc($t['fullname'])."</option>";
  }
  ?>
</select>



      <button type="submit" name="add_meter">Add IAMMETER Meter</button>
    </form>

    <hr class="divider">

    <!-- WATER Meter Form (BUG FIXED: tenant select name) -->
    <h3>Add WATER Meter</h3>
    <form method="POST" action="add_water_meter.php">
      <input name="serial_number" placeholder="Water Serial Number" required>
      <input name="description"   placeholder="Description (e.g. Kitchen Tap)">

      <select name="property_id" required>
        <option value="">Assign to Property</option>
        <?php
        if ($isAgent && $hasAgentProps) {
          $stmt = $conn_rbe->prepare("SELECT id, property_number FROM properties WHERE agent_id = :aid ORDER BY property_number ASC");
          $stmt->execute([':aid'=>$agent_id]);
        } else {
          $stmt = $conn_rbe->query("SELECT id, property_number FROM properties ORDER BY property_number ASC");
        }
        while ($prop = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo "<option value='".(int)$prop['id']."'>".esc($prop['property_number'])."</option>";
        }
        ?>
      </select>

      <select name="landlord_id" required>
        <option value="">Assign to Landlord</option>
        <?php
        if ($isAgent && $hasAgentProps) {
          $stmt = $conn_rbe->prepare("
            SELECT DISTINCT u.id, u.fullname
            FROM rbe_users u
            JOIN rbe_roles r ON r.user_id=u.id AND r.role='landlord'
            JOIN properties p ON p.landlord_id = u.id
            WHERE p.agent_id = :aid
            ORDER BY u.fullname ASC
          ");
          $stmt->execute([':aid'=>$agent_id]);
        } else {
          $stmt = $conn_rbe->query("
            SELECT u.id, u.fullname
            FROM rbe_users u
            JOIN rbe_roles r ON u.id = r.user_id AND r.role='landlord'
            ORDER BY u.fullname ASC
          ");
        }
        while ($ll = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo "<option value='".(int)$ll['id']."'>".esc($ll['fullname'])."</option>";
        }
        ?>
      </select>

      <!-- FIXED: this was incorrectly named landlord_id before -->
      <select name="tenant_id" required>
        <option value="">Assign to Tenant</option>
        <?php
        $stmt = $conn_rbe->query("
          SELECT u.id, u.fullname
          FROM rbe_users u
          JOIN rbe_roles r ON u.id = r.user_id AND r.role='tenant'
          ORDER BY u.fullname ASC
        ");
        while ($tn = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo "<option value='".(int)$tn['id']."'>".esc($tn['fullname'])."</option>";
        }
        ?>
      </select>

      <button type="submit">Add WATER Meter</button>
      <!-- Tip: in add_water_meter.php, mirror the agent_id insert pattern if column exists -->
    </form>

    <hr class="divider">

    <!-- FLECTO Meter Form -->
    <h3>Add FLECTO Meter</h3>
    <form method="post" action="">
      <input type="text" name="serial_number" placeholder="Flecto Serial Number" required>
      <input type="text" name="description"   placeholder="Description (e.g. Sub DB)" required>

      <select name="property_id" required>
        <option value="">Assign to Property</option>
        <?php
        if ($isAgent && $hasAgentProps) {
          $stmt = $conn_rbe->prepare("SELECT id, property_number FROM properties WHERE agent_id = :aid ORDER BY property_number ASC");
          $stmt->execute([':aid'=>$agent_id]);
        } else {
          $stmt = $conn_rbe->query("SELECT id, property_number FROM properties ORDER BY property_number ASC");
        }
        while ($prop = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo "<option value='".(int)$prop['id']."'>".esc($prop['property_number'])."</option>";
        }
        ?>
      </select>

      <select name="landlord_id" required>
        <option value="">Assign to Landlord</option>
        <?php
        if ($isAgent && $hasAgentProps) {
          $stmt = $conn_rbe->prepare("
            SELECT DISTINCT u.id, u.fullname
            FROM rbe_users u
            JOIN rbe_roles r ON r.user_id=u.id AND r.role='landlord'
            JOIN properties p ON p.landlord_id = u.id
            WHERE p.agent_id = :aid
            ORDER BY u.fullname ASC
          ");
          $stmt->execute([':aid'=>$agent_id]);
        } else {
          $stmt = $conn_rbe->query("
            SELECT u.id, u.fullname
            FROM rbe_users u
            JOIN rbe_roles r ON u.id = r.user_id AND r.role='landlord'
            ORDER BY u.fullname ASC
          ");
        }
        while ($ll = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo "<option value='".(int)$ll['id']."'>".esc($ll['fullname'])."</option>";
        }
        ?>
      </select>

      <select name="tenant_id" required>
        <option value="">Assign to Tenant</option>
        <?php
        $stmt = $conn_rbe->query("
          SELECT u.id, u.fullname
          FROM rbe_users u
          JOIN rbe_roles r ON u.id = r.user_id AND r.role='tenant'
          ORDER BY u.fullname ASC
        ");
        while ($t = $stmt->fetch(PDO::FETCH_ASSOC)) {
          echo "<option value='".(int)$t['id']."'>".esc($t['fullname'])."</option>";
        }
        ?>
      </select>

      <button type="submit" name="add_flecto_meter">Add FLECTO Meter</button>
    </form>
  </div>

  <div class="section">
    <section>
      <h1>Existing Meters</h1>
    </section>

    <!-- IAMMETER LIST -->
    <section style="margin-top:40px;">
      <h3 style="color:#7ed957;margin-bottom:20px;">⚡ IAMMETER Meters</h3>
      <?php
      $page_iam = positiveInt($_GET['page_iam'] ?? 1);
      $offset_iam = ($page_iam - 1) * $limit;

      if ($isAgent && $hasAgentSmart) {
          $total_stmt = $conn_rbe->prepare("
            SELECT COUNT(*) FROM smart_meters 
            WHERE source_type='IAMMETER' AND meter_type='electricity' AND agent_id = :aid
          ");
          $total_stmt->execute([':aid'=>$agent_id]);
      } else {
          $total_stmt = $conn_rbe->query("
            SELECT COUNT(*) FROM smart_meters 
            WHERE source_type='IAMMETER' AND meter_type='electricity'
          ");
      }
      $total = (int)$total_stmt->fetchColumn();
      $total_pages_iam = max(1, (int)ceil($total / $limit));

      if ($isAgent && $hasAgentSmart) {
        $stmt = $conn_rbe->prepare("
          SELECT m.id, m.serial, m.phases, p.property_number 
          FROM smart_meters m
          LEFT JOIN properties p ON m.property_id = p.id 
          WHERE m.source_type='IAMMETER' AND m.meter_type='electricity' AND m.agent_id = :aid
          ORDER BY m.serial ASC
          LIMIT $limit OFFSET $offset_iam
        ");
        $stmt->execute([':aid'=>$agent_id]);
      } else {
        $stmt = $conn_rbe->query("
          SELECT m.id, m.serial, m.phases, p.property_number 
          FROM smart_meters m
          LEFT JOIN properties p ON m.property_id = p.id 
          WHERE m.source_type='IAMMETER' AND m.meter_type='electricity'
          ORDER BY m.serial ASC
          LIMIT $limit OFFSET $offset_iam
        ");
      }
      ?>
      <table>
        <tr>
          <th>Serial</th>
          <th>Phases</th>
          <th>Property</th>
          <th>Actions</th>
        </tr>
        <?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)): ?>
          <tr>
            <td><?= esc($row['serial']) ?></td>
            <td><?= (int)$row['phases'] ?></td>
            <td><?= esc($row['property_number'] ?? 'Unassigned') ?></td>
            <td>
              <a href="reassign_meter.php?id=<?= (int)$row['id'] ?>">Reassign</a> |
              <a href="delete_meter.php?id=<?= (int)$row['id'] ?>" style="color:#ff6666;">Delete</a>
            </td>
          </tr>
        <?php endwhile; ?>
      </table>
      <div style="text-align:center;margin-top:20px;">
        <?php if ($page_iam > 1): ?>
          <a href="?page_iam=<?= $page_iam - 1 ?>" style="color:#7ed957;margin:0 10px;">« Prev</a>
        <?php endif; ?>
        <span>Page <?= $page_iam ?> of <?= $total_pages_iam ?></span>
        <?php if ($page_iam < $total_pages_iam): ?>
          <a href="?page_iam=<?= $page_iam + 1 ?>" style="color:#7ed957;margin:0 10px;">Next »</a>
        <?php endif; ?>
      </div>
    </section>

    <hr class="divider">

    <!-- FLECTO LIST -->
    <section style="margin-top:40px;">
      <h3 style="color:#7ed957;margin-bottom:20px;">⚡ FLECTO Meters</h3>
      <?php
      $page_flecto = positiveInt($_GET['page_flecto'] ?? 1);
      $offset_f = ($page_flecto - 1) * $limit;

      if ($isAgent && $hasAgentFlecto) {
        $total_stmt = $conn_rbe->prepare("SELECT COUNT(*) FROM flecto_meters WHERE is_active=1 AND agent_id = :aid");
        $total_stmt->execute([':aid'=>$agent_id]);
      } else {
        $total_stmt = $conn_rbe->query("SELECT COUNT(*) FROM flecto_meters WHERE is_active=1");
      }
      $total_flecto = (int)$total_stmt->fetchColumn();
      $total_pages_f = max(1, (int)ceil($total_flecto / $limit));

      if ($isAgent && $hasAgentFlecto) {
        $stmt = $conn_rbe->prepare("
          SELECT f.id, f.serial_number, f.description, p.property_number
          FROM flecto_meters f
          LEFT JOIN properties p ON f.property_id = p.id
          WHERE f.is_active=1 AND f.agent_id = :aid
          ORDER BY f.serial_number ASC
          LIMIT $limit OFFSET $offset_f
        ");
        $stmt->execute([':aid'=>$agent_id]);
      } else {
        $stmt = $conn_rbe->query("
          SELECT f.id, f.serial_number, f.description, p.property_number
          FROM flecto_meters f
          LEFT JOIN properties p ON f.property_id = p.id
          WHERE f.is_active=1
          ORDER BY f.serial_number ASC
          LIMIT $limit OFFSET $offset_f
        ");
      }
      ?>
      <table>
        <tr>
          <th>Serial</th>
          <th>Description</th>
          <th>Property</th>
          <th>Actions</th>
        </tr>
        <?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)): ?>
          <tr>
            <td><?= esc($row['serial_number']) ?></td>
            <td><?= esc($row['description'] ?? '—') ?></td>
            <td><?= esc($row['property_number'] ?? 'Unassigned') ?></td>
            <td>
              <a href="reassign_flecto_meter.php?id=<?= (int)$row['id'] ?>">Reassign</a> |
              <a href="delete_flecto_meter.php?id=<?= (int)$row['id'] ?>" style="color:#ff6666;">Delete</a>
            </td>
          </tr>
        <?php endwhile; ?>
      </table>
      <div style="text-align:center;margin-top:20px;">
        <?php if ($page_flecto > 1): ?>
          <a href="?page_flecto=<?= $page_flecto - 1 ?>" style="color:#7ed957;margin:0 10px;">« Prev</a>
        <?php endif; ?>
        <span>Page <?= $page_flecto ?> of <?= $total_pages_f ?></span>
        <?php if ($page_flecto < $total_pages_f): ?>
          <a href="?page_flecto=<?= $page_flecto + 1 ?>" style="color:#7ed957;margin:0 10px;">Next »</a>
        <?php endif; ?>
      </div>
    </section>

    <hr class="divider">

    <!-- WATER LIST -->
    <section style="margin-top:40px;">
      <h3 style="color:#7ed957;margin-bottom:20px;">💧 WATER Meters</h3>
      <?php
      $page_w = positiveInt($_GET['page'] ?? 1);
      $offset_w = ($page_w - 1) * $limit;

      $search_serial = trim($_GET['search_serial'] ?? '');
      $where_clause = "w.is_active = 1";
      $params = [];

      if ($isAgent && $hasAgentWater) {
        $where_clause .= " AND w.agent_id = :aid";
        $params[':aid'] = $agent_id;
      }
      if ($search_serial !== '') {
        $where_clause .= " AND w.serial_number LIKE :ser";
        $params[':ser'] = "%$search_serial%";
      }

      $total_stmt = $conn_rbe->prepare("SELECT COUNT(*) FROM water_meters w WHERE $where_clause");
      $total_stmt->execute($params);
      $total_meters = (int)$total_stmt->fetchColumn();
      $total_pages_w = max(1, (int)ceil($total_meters / $limit));

      $sql = "
        SELECT w.id, w.serial_number, w.description, w.landlord_id, u.fullname AS landlord_name, p.property_number
        FROM water_meters w
        LEFT JOIN properties p ON w.property_id = p.id
        LEFT JOIN rbe_users u ON w.landlord_id = u.id
        WHERE $where_clause
        ORDER BY w.serial_number ASC
        LIMIT $limit OFFSET $offset_w
      ";
      $stmt = $conn_rbe->prepare($sql);
      $stmt->execute($params);
      ?>
      <form method="get" style="margin-bottom:20px;text-align:center;">
        <input type="text" name="search_serial" placeholder="Serial Number..." value="<?= esc($_GET['search_serial'] ?? '') ?>" style="padding:8px;border-radius:6px;width:180px;">
        <button type="submit" style="padding:8px 12px;background:#7ed957;color:black;border:none;border-radius:6px;cursor:pointer;">Search</button>
      </form>

      <table>
        <tr>
          <th>Serial</th>
          <th>Landlord</th>
          <th>Property</th>
          <th>Actions</th>
        </tr>
        <?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)): ?>
          <tr>
            <td><?= esc($row['serial_number']) ?></td>
            <td><?= esc($row['landlord_name'] ?? 'Unassigned') ?></td>
            <td><?= esc($row['property_number'] ?? 'Unassigned') ?></td>
            <td>
              <a href="reassign_water_meter.php?id=<?= (int)$row['id'] ?>">Reassign</a> |
              <a href="delete_water_meter.php?id=<?= (int)$row['id'] ?>" style="color:#ff6666;">Delete</a>
            </td>
          </tr>
        <?php endwhile; ?>
      </table>

      <div style="text-align:center;margin-top:20px;">
        <?php if ($page_w > 1): ?>
          <a href="?page=<?= $page_w - 1 ?>&search_serial=<?= urlencode($search_serial) ?>" style="color:#7ed957;margin:0 10px;">« Prev</a>
        <?php endif; ?>
        <span>Page <?= $page_w ?> of <?= $total_pages_w ?></span>
        <?php if ($page_w < $total_pages_w): ?>
          <a href="?page=<?= $page_w + 1 ?>&search_serial=<?= urlencode($search_serial) ?>" style="color:#7ed957;margin:0 10px;">Next »</a>
        <?php endif; ?>
      </div>
    </section>
  </div>
</body>
</html>
