<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once __DIR__ . '/core/db_connect.php';
require_once __DIR__ . '/core/functions.php';
require_once __DIR__ . '/modules/billing/includes/energy_engine.php';

// Access control: admin override, otherwise landlord
$role = null; $landlord_id = null;
if (isset($_GET['landlord_id']) && isset($_SESSION['user_id'])) {
    $admin_id = (int)$_SESSION['user_id'];
    $stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
    $stmt->execute([$admin_id]);
    if ($stmt->fetchColumn() === 'admin') { $role = 'admin'; $landlord_id = (int)$_GET['landlord_id']; } else { exit('Access denied.'); }
} elseif (isset($_SESSION['user_id'])) {
    $landlord_id = (int)$_SESSION['user_id'];
    $stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
    $stmt->execute([$landlord_id]);
    if ($stmt->fetchColumn() === 'landlord') { $role = 'landlord'; } else { exit('Access denied.'); }
} else {
    header('Location: login.php');
    exit();
}

// Include landlord sidebar navigation (must be after redirects)
include 'landlord-nav.php';

// Landlord Profile
$stmt = $conn_rbe->prepare("SELECT fullname, email, phone, use_wallet FROM rbe_users WHERE id = ?");
$stmt->execute([$landlord_id]);
$landlord_profile = $stmt->fetch(PDO::FETCH_ASSOC) ?: ['fullname'=>'','email'=>'','phone'=>'','use_wallet'=>0];
$landlord_wallet_enabled = (int)($landlord_profile['use_wallet'] ?? 0);

// Tenants and Properties
$stmt = $conn_rbe->prepare("SELECT tlm.tenant_id, u.fullname FROM tenant_landlord_map tlm JOIN rbe_users u ON tlm.tenant_id = u.id WHERE tlm.landlord_id = ?");
$stmt->execute([$landlord_id]);
$tenants = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $conn_rbe->prepare("SELECT * FROM properties WHERE landlord_id = ?");
$stmt->execute([$landlord_id]);
$properties = $stmt->fetchAll(PDO::FETCH_ASSOC);

function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function has_table(PDO $pdo, string $table): bool { try { $q = $pdo->prepare('SHOW TABLES LIKE ?'); $q->execute([$table]); return (bool)$q->fetchColumn(); } catch (Throwable $e) { return false; } }

// ================================
// Helper queries for tenant metrics
// ================================
function getIAMMeterData(PDO $db, int $tenant_id): array {
  $res = ['power_now'=>0.0,'energy_today_kwh'=>0.0,'kva_now'=>0.0];
  $m = $db->prepare("SELECT id FROM smart_meters WHERE tenant_id=?");
  $m->execute([$tenant_id]);
  $meters = $m->fetchAll(PDO::FETCH_COLUMN);
  if (!$meters) return $res;
  $today = date('Y-m-d');
  foreach ($meters as $mid) {
    // Power now at latest timestamp (sum across phases)
    $st = $db->prepare("SELECT reading_timestamp FROM smart_meter_readings WHERE meter_id=? ORDER BY reading_timestamp DESC LIMIT 1");
    $st->execute([$mid]);
    if ($ts = $st->fetchColumn()) {
      $p = $db->prepare("SELECT SUM(power) AS p, AVG(NULLIF(power_factor,0)) AS pf FROM smart_meter_readings WHERE meter_id=? AND reading_timestamp=?");
      $p->execute([$mid, $ts]);
      $row = $p->fetch(PDO::FETCH_ASSOC) ?: ['p'=>0,'pf'=>null];
      $res['power_now'] += (float)($row['p'] ?? 0);
      $pf = (float)($row['pf'] ?? 0);
      if ($pf > 0) $res['kva_now'] += ((float)$row['p']) / $pf;
    }
    // Energy today: delta between first and last timestamps today (sum across phases)
    $t1 = $db->prepare("SELECT reading_timestamp FROM smart_meter_readings WHERE meter_id=? AND reading_timestamp BETWEEN ? AND ? GROUP BY reading_timestamp HAVING COUNT(DISTINCT phase)>=1 ORDER BY reading_timestamp ASC LIMIT 1");
    $t1->execute([$mid, "$today 00:00:00", "$today 23:59:59"]);
    $first = $t1->fetchColumn();
    $t2 = $db->prepare("SELECT reading_timestamp FROM smart_meter_readings WHERE meter_id=? AND reading_timestamp BETWEEN ? AND ? GROUP BY reading_timestamp HAVING COUNT(DISTINCT phase)>=1 ORDER BY reading_timestamp DESC LIMIT 1");
    $t2->execute([$mid, "$today 00:00:00", "$today 23:59:59"]);
    $last = $t2->fetchColumn();
    if ($first && $last && $first !== $last) {
      $s1 = $db->prepare("SELECT SUM(energy_total) FROM smart_meter_readings WHERE meter_id=? AND reading_timestamp=?");
      $s1->execute([$mid, $first]);
      $v1 = (float)$s1->fetchColumn();
      $s2 = $db->prepare("SELECT SUM(energy_total) FROM smart_meter_readings WHERE meter_id=? AND reading_timestamp=?");
      $s2->execute([$mid, $last]);
      $v2 = (float)$s2->fetchColumn();
      $delta_wh = max(0.0, $v2 - $v1);
      $res['energy_today_kwh'] += ($delta_wh / 1000.0);
    }
  }
  return $res;
}

function getFlectoData(PDO $db, int $tenant_id): array {
  $res = ['power_now'=>0.0,'energy_today_kwh'=>0.0];
  $m = $db->prepare("SELECT serial_number FROM flecto_meters WHERE tenant_id=?");
  $m->execute([$tenant_id]);
  $serials = $m->fetchAll(PDO::FETCH_COLUMN);
  if (!$serials) return $res;
  $today = date('Y-m-d');
  foreach ($serials as $sn) {
    $r = $db->prepare("SELECT reg_a,reg_h,reg_l,created_at FROM flecto_meter_readings WHERE serial=? ORDER BY created_at DESC LIMIT 2");
    $r->execute([$sn]);
    $rows = $r->fetchAll(PDO::FETCH_ASSOC);
    if (count($rows) >= 2) {
      // Use unified import registers only for instantaneous power estimation
      $sum = fn($row) => (float)$row['reg_a'] + (float)$row['reg_h'] + (float)$row['reg_l'];
      $v2 = $sum($rows[0]); $t2 = strtotime((string)$rows[0]['created_at']);
      $v1 = $sum($rows[1]); $t1 = strtotime((string)$rows[1]['created_at']);
      $delta = max(0.0, $v2 - $v1);
      $dt = max(1, $t2 - $t1) / 3600.0; // hours
      $kw = $delta / $dt; // average kW
      $res['power_now'] += max(0.0, $kw * 1000.0); // approx W
    }
    // Today window using created_at
    $sA = $db->prepare("SELECT * FROM flecto_meter_readings WHERE serial=? AND created_at BETWEEN ? AND ? ORDER BY created_at ASC LIMIT 1");
    $sA->execute([$sn, "$today 00:00:00", "$today 23:59:59"]);
    $first = $sA->fetch(PDO::FETCH_ASSOC);
    $sB = $db->prepare("SELECT * FROM flecto_meter_readings WHERE serial=? AND created_at BETWEEN ? AND ? ORDER BY created_at DESC LIMIT 1");
    $sB->execute([$sn, "$today 00:00:00", "$today 23:59:59"]);
    $last = $sB->fetch(PDO::FETCH_ASSOC);
    if ($first && $last) {
      // Unified energy engine: import registers (reg_a + reg_h + reg_l) only
      $sum = fn($row) => (float)$row['reg_a'] + (float)$row['reg_h'] + (float)$row['reg_l'];
      $res['energy_today_kwh'] += max(0.0, $sum($last) - $sum($first));
    }
  }
  return $res;
}

function getFlectoEnergySplit(PDO $db, int $tenant_id, string $start, string $end, bool $touEnabled): array {
  $energy = get_energy_breakdown($db, $tenant_id, null, null, null, $start, $end, $touEnabled);
  $t = $energy['tenant'] ?? [];
  return [
    'grid_kwh'  => (float)($t['import_t1'] ?? 0),
    'gen_kwh'   => (float)($t['import_t2'] ?? 0),
    'solar_kwh' => (float)($t['solar_export'] ?? 0),
  ];
}

function getWaterData(PDO $db, int $tenant_id): array {
  $res = ['water_today_kl'=>0.0];
  $m = $db->prepare("SELECT serial_number FROM water_meters WHERE tenant_id=?");
  $m->execute([$tenant_id]);
  $serials = $m->fetchAll(PDO::FETCH_COLUMN);
  if (!$serials) return $res;
  $today = date('Y-m-d');
  foreach ($serials as $sn) {
    $s = $db->prepare("SELECT MIN(volume_liters) AS vmin, MAX(volume_liters) AS vmax FROM water_meter_readings WHERE serial_number=? AND reading_datetime BETWEEN ? AND ?");
    $s->execute([$sn, "$today 00:00:00", "$today 23:59:59"]);
    [$vmin,$vmax] = $s->fetch(PDO::FETCH_NUM) ?: [null,null];
    if ($vmin !== null && $vmax !== null) {
      $res['water_today_kl'] += max(0.0, ((float)$vmax - (float)$vmin)/1000.0);
    }
  }
  return $res;
}

function getLandlordAlerts(PDO $db, int $landlord_id, int $limit = 10): array {
  try {

    $sql = "
      SELECT 
        source AS type,
        serial_number AS meter,
        property_number AS property,
        tenant_id,
        last_synced_at
      FROM vw_meters_combined
      WHERE 
        landlord_id = ?
        AND (
          last_synced_at IS NULL
          OR last_synced_at = '0000-00-00 00:00:00'
          OR CONVERT_TZ(last_synced_at, '+00:00', '+02:00') < (NOW() - INTERVAL 2 HOUR)
        )
      ORDER BY last_synced_at ASC
      LIMIT {$limit}
    ";

    $stmt = $db->prepare($sql);
    $stmt->execute([$landlord_id]);

    $rows = [];

    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {

      $ts = $r['last_synced_at'];

      // FIX: Convert UTC -> SAST (+2 hours)
      $lastSync = $ts ? strtotime($ts . ' UTC') + 7200 : 0;

      if ($lastSync > 0) {
        $diff  = time() - $lastSync;
        $hours = floor($diff / 3600);
        $mins  = floor(($diff % 3600) / 60);
        $ago   = ($hours > 0 ? "{$hours}h " : '') . "{$mins}m ago";
      } else {
        $ago = 'Never synced';
      }

      // FIX: Status now correctly aligned to SAST
      $status = ($lastSync === 0 || $lastSync < (time() - 86400))
        ? 'offline'
        : 'late';

      $rows[] = [
        'type'     => $r['type'],
        'meter'    => $r['meter'],
        'property' => $r['property'] ?: 'Unknown',
        'time'     => ($lastSync > 0 ? date('Y-m-d H:i', $lastSync) : '-'),
        'ago'      => $ago,
        'status'   => $status,
        'tenant_id'=> (int)($r['tenant_id'] ?? 0),
      ];
    }

    return $rows;

  } catch (Throwable $e) {
    return [];
  }
}


function getBillingSummary(PDO $db, int $landlord_id, int $tenant_id, float $kwh, float $kl, array $tiers_elec, array $tiers_water, ?float $elec_cost_override = null): array {
  // Prefer tenant-specific settings else landlord global
  $st = $db->prepare("SELECT * FROM billing_settings WHERE landlord_id=? AND tenant_id=? ORDER BY id DESC LIMIT 1");
  $st->execute([$landlord_id, $tenant_id]);
  $s = $st->fetch(PDO::FETCH_ASSOC);
  if (!$s) {
    $st = $db->prepare("SELECT * FROM billing_settings WHERE landlord_id=? AND tenant_id IS NULL ORDER BY id DESC LIMIT 1");
    $st->execute([$landlord_id]);
    $s = $st->fetch(PDO::FETCH_ASSOC) ?: [];
  }
  $buy = (float)($s['buy_rate'] ?? 0);
  $water_rate = (float)($s['water_rate'] ?? 0);
  $fees = (
    (float)($s['sewage_fee'] ?? 0) +
    (float)($s['refuse_removal_fee'] ?? 0) +
    (float)($s['rates_and_taxes'] ?? 0) +
    (float)($s['other_fee'] ?? 0) + (float)($s['other_fee_2'] ?? 0) + (float)($s['other_fee_3'] ?? 0) + (float)($s['other_fee_4'] ?? 0) + (float)($s['other_fee_5'] ?? 0)
  );
  // Apply tiers if available, else flat buy rate (unless overridden)
  if ($elec_cost_override !== null) {
    $elec_cost = round($elec_cost_override, 2);
  } else {
    $elec_cost = $tiers_elec ? calculate_tiered_cost($kwh, $tiers_elec) : round($kwh * $buy, 2);
  }
  $water_cost = $tiers_water ? calculate_tiered_cost($kl, $tiers_water) : round($kl * $water_rate, 2);
  return ['elec_cost'=>$elec_cost,'water_cost'=>$water_cost,'fees'=>$fees,'total'=>round($elec_cost + $water_cost + $fees,2)];
}

// Preload tiers (landlord scope)
$tiers_electricity = [];
$tiers_water       = [];
$tiers_generator   = [];
$tiers_solar       = [];
try {
  $q = $conn_rbe->prepare("SELECT * FROM billing_tiers WHERE landlord_id=? ORDER BY type, tier_from ASC");
  $q->execute([$landlord_id]);
  foreach ($q->fetchAll(PDO::FETCH_ASSOC) as $t) {
    $type = strtolower((string)$t['type']);
    if ($type === 'electricity') { $tiers_electricity[] = $t; }
    if ($type === 'water')       { $tiers_water[]       = $t; }
    if ($type === 'generator')   { $tiers_generator[]   = $t; }
    if ($type === 'solar')       { $tiers_solar[]       = $t; }
  }
} catch (Throwable $e) { /* ignore */ }

// KPI aggregates (quick counts)
$kpi_tenants = count($tenants);
$kpi_properties = count($properties);

// Meter counts per tenant (basic)
$tenant_iammeters = []; $tenant_flecto_meters = []; $tenant_water_meters = [];
foreach ($tenants as $t) {
    $tid = (int)$t['tenant_id'];
    $stmt = $conn_rbe->prepare("SELECT COUNT(*) FROM smart_meters WHERE tenant_id = ? AND source_type = 'IAMMETER'");
    $stmt->execute([$tid]);
    $tenant_iammeters[$tid] = (int)$stmt->fetchColumn();

    $stmt = $conn_rbe->prepare("SELECT COUNT(*) FROM flecto_meters WHERE tenant_id = ?");
    $stmt->execute([$tid]);
    $tenant_flecto_meters[$tid] = (int)$stmt->fetchColumn();

    $stmt = $conn_rbe->prepare("SELECT COUNT(*) FROM water_meters WHERE tenant_id = ?");
    $stmt->execute([$tid]);
    $tenant_water_meters[$tid] = (int)$stmt->fetchColumn();
}
$kpi_iam = array_sum($tenant_iammeters);
$kpi_flecto = array_sum($tenant_flecto_meters);
$kpi_water_meters = array_sum($tenant_water_meters);

// Billing Snapshot
$fee_modes = [];
$stmt = $conn_rbe->prepare('SELECT fee_type, mode FROM billing_fee_modes WHERE landlord_id = ?');
$stmt->execute([$landlord_id]);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { $fee_modes[strtolower(trim((string)$row['fee_type']))] = $row['mode']; }

$extra_fees_summary = []; $has_extra_fees = has_table($conn_rbe, 'extra_fees');
if ($has_extra_fees) {
    $tenant_ids = array_map('intval', array_column($tenants, 'tenant_id'));
    if ($tenant_ids) {
        $in = implode(',', array_fill(0, count($tenant_ids), '?'));
        $stmt = $conn_rbe->prepare("SELECT tenant_id, fee_type, active FROM extra_fees WHERE landlord_id = ? AND ((tenant_id IN ($in)) OR tenant_id IS NULL)");
        $params = array_merge([$landlord_id], $tenant_ids);
        $stmt->execute($params);
    } else {
        $stmt = $conn_rbe->prepare('SELECT tenant_id, fee_type, active FROM extra_fees WHERE landlord_id = ? AND tenant_id IS NULL');
        $stmt->execute([$landlord_id]);
    }
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $ef) {
        if ((int)$ef['active'] !== 1) continue;
        $t = strtolower(trim((string)$ef['fee_type']));
        if (!isset($extra_fees_summary[$t])) $extra_fees_summary[$t] = ['global'=>0,'tenant'=>0];
        if (is_null($ef['tenant_id'])) $extra_fees_summary[$t]['global']++; else $extra_fees_summary[$t]['tenant']++;
    }
}

$landlord_alerts = getLandlordAlerts($conn_rbe, $landlord_id, 20);

// Flecto meters list for dropdown
$flecto_control_meters = [];
try {
  $stmt = $conn_rbe->prepare("
    SELECT fm.serial_number
    FROM flecto_meters fm
    JOIN tenant_landlord_map tlm ON tlm.tenant_id = fm.tenant_id
    WHERE tlm.landlord_id = ?
    ORDER BY fm.serial_number ASC
  ");
  $stmt->execute([$landlord_id]);
  $flecto_control_meters = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) {
  $flecto_control_meters = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Landlord Dashboard - RBE</title>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="/assets/css/theme.css">
  <style>
    body { font-family: 'Inter','Segoe UI',sans-serif; background: linear-gradient(180deg, #051a25 0%, #0b2030 100%); color: #e9eef5; margin:0; padding:30px; margin-left:240px; }
    @media (max-width:900px){ body{ margin-left:0; } }
    body.sidebar-collapsed{ margin-left:72px; }
    @media (max-width:900px){ body.sidebar-collapsed{ margin-left:0; } }
    h1,h2,h3 { font-weight:600; letter-spacing:0.4px; color:#7ed957; margin-top:0; }
    h2 { font-size:20px; margin-bottom:12px; }
    h3 { font-size:17px; color:#00ccff; margin-bottom:10px; }
    .card { background:#112537; padding:28px 32px; border-radius:14px; box-shadow:0 4px 14px rgba(0,0,0,0.35); margin:25px auto; max-width:1100px; }
    .property-section { background:#0b1f30; padding:18px 24px; border-radius:10px; margin-top:25px; border:1px solid rgba(126,217,87,0.15); box-shadow:0 2px 6px rgba(0,0,0,0.25); }
    .nav { display:flex; flex-wrap:wrap; justify-content:center; gap:15px; margin:0 auto 20px auto; max-width:1100px; }
    .nav a, .nav-btn, .btn { display:inline-block; background:linear-gradient(90deg,#7ed957 0%,#9eff6d 100%); color:#0a1b25; font-weight:600; padding:10px 24px; border-radius:30px; text-decoration:none; transition:0.2s; border:none; cursor:pointer; }
    .nav a:hover, .nav-btn:hover, .btn:hover { transform:translateY(-1px); box-shadow:0 0 10px rgba(126,217,87,0.4); }
    .profile-grid { display:grid; grid-template-columns: repeat(auto-fit,minmax(320px,1fr)); gap:30px; margin-top:20px; }
    .profile-box { background:#122c4c; border-radius:12px; padding:20px; box-shadow:0 3px 10px rgba(0,0,0,0.4); }
    .profile-field { margin-bottom:15px; }
    .profile-field .label { display:block; font-weight:500; color:#7ed957; margin-bottom:6px; font-size:1.05em; }
    .profile-field .value { color:#fff; font-size:1.05em; line-height:1.5; }
    .list-unstyled { list-style:none; padding-left:0; margin:0; }
    .kpi-grid { display:grid; grid-template-columns: repeat(auto-fit,minmax(180px,1fr)); gap:12px; }
    .kpi { background:#0b1f30; border:1px solid rgba(126,217,87,0.15); border-radius:10px; padding:12px 14px; }
    .kpi .label { color:#9ec3d9; font-size:12px; }
    .kpi .value { font-size:20px; color:#7ed957; font-weight:600; }
    table { width:100%; border-collapse:collapse; background:#0b1f33; color:#fff; margin-top:12px; font-size:0.95em; }
    th, td { padding:10px; border-bottom:1px solid rgba(255,255,255,0.08); text-align:center; }
    th { background:#1b3a4d; color:#7ed957; }
    .inp { width:100%; padding:10px; border-radius:6px; border:1px solid rgba(126,217,87,0.25); background:#0b2234; color:#fff; }
    .inp:focus { outline:none; border-color:#7ed957; box-shadow:0 0 4px rgba(126,217,87,0.4); }
    .search-row { display:flex; gap:10px; justify-content:flex-end; align-items:center; }
    .view-address-btn { background:#7ed957; color:#0a1b25; border:none; padding:6px 10px; border-radius:8px; cursor:pointer; }

    .alerts-controls { display:flex; gap:10px; justify-content:space-between; align-items:center; margin-bottom:8px; flex-wrap:wrap; }
    .alerts-controls select { max-width:200px; }
    .alert-badge { display:inline-block; padding:3px 7px; border-radius:6px; font-size:12px; font-weight:600; color:#000; }
    .alert-green  { background:#48e072; }
    .alert-yellow { background:#ffcc00; }
    .alert-red    { background:#ff4d4f; }

    .control-row { display:flex; gap:12px; flex-wrap:wrap; align-items:center; margin-top:10px; }
    .btn-outline { background:transparent; border:1px solid rgba(126,217,87,0.55); color:#e9eef5; padding:10px 18px; border-radius:30px; font-weight:600; cursor:pointer; transition:0.2s; }
    .btn-outline:hover { transform:translateY(-1px); box-shadow:0 0 10px rgba(126,217,87,0.25); }

    .toggle-btn { padding:10px 18px; border-radius:30px; font-weight:700; border:1px solid rgba(255,255,255,0.12); cursor:pointer; transition:0.2s; color:#0a1b25; }
    .toggle-btn.on  { background:#48e072; }
    .toggle-btn.off { background:#ff4d4f; }
    .toggle-meta { color:#9ec3d9; font-size:12px; margin-top:8px; line-height:1.4; }

    .meter-select-wrap { display:flex; flex-direction:column; gap:6px; margin-top:10px; }
    .meter-select-wrap label { color:#9ec3d9; font-size:12px; }
  </style>
</head>
<body>

<?php if ($role !== 'landlord'): ?>
  <a href="<?= ($role === 'admin') ? 'admin-dashboard.php' : 'landlord-dashboard.php' ?>" class="nav-btn">Back to Dashboard</a>
<?php endif; ?>

<div class="card">
  <h2>Overview</h2>
  <div class="kpi-grid">
    <div class="kpi"><div class="label">Tenants</div><div class="value"><?= number_format($kpi_tenants) ?></div></div>
    <div class="kpi"><div class="label">Properties</div><div class="value"><?= number_format($kpi_properties) ?></div></div>
    <div class="kpi"><div class="label">IAMMETER</div><div class="value"><?= number_format($kpi_iam) ?></div></div>
    <div class="kpi"><div class="label">FLECTO</div><div class="value"><?= number_format($kpi_flecto) ?></div></div>
    <div class="kpi"><div class="label">Water Meters</div><div class="value"><?= number_format($kpi_water_meters) ?></div></div>
  </div>
</div>

<div class="card">
  <h2>Billing Snapshot</h2>
  <div>
    <strong>Modes</strong> -
    Sewage: <?= esc($fee_modes['sewage'] ?? 'n/a') ?>,
    Refuse: <?= esc($fee_modes['refuse'] ?? 'n/a') ?>,
    Rates: <?= esc($fee_modes['rates'] ?? 'n/a') ?>
  </div>
  <div style="margin-top:8px;">
    <strong>Extra Utility Fees</strong> -
    <?php if ($has_extra_fees && $extra_fees_summary): ?>
      <?php foreach ($extra_fees_summary as $t => $c): ?>
        <span class="tag" style="display:inline-block; margin:4px 8px 0 0; padding:2px 10px; border:1px solid #7ed957; border-radius:999px; color:#7ed957;">
          <?= esc($t) ?>: Global <?= (int)$c['global'] ?> / Tenants <?= (int)$c['tenant'] ?>
        </span>
      <?php endforeach; ?>
    <?php else: ?>
      <span style="color:#9ec3d9;">No extra fee configuration found.</span>
    <?php endif; ?>
  </div>
  <div style="margin-top:10px; text-align:right;">
    <a class="btn" href="/modules/billing/billing.php?landlord_id=<?= $landlord_id ?>">Manage Billing</a>
  </div>
</div>

<div class="card">
  <h2>Alerts &amp; Offline Meters</h2>
  <div class="alerts-controls">
    <div style="color:#9ec3d9; font-size:13px;">
      Showing meters that have not synced in the last 2+ hours.
    </div>
    <div>
      <label for="alertTypeFilter" style="margin-right:6px;">Filter by type:</label>
      <select id="alertTypeFilter" class="inp" style="max-width:200px;">
        <option value="ALL">All Types</option>
        <option value="IAMMETER">IAMMETER</option>
        <option value="FLECTO">FLECTO</option>
        <option value="WATER">WATER</option>
      </select>
    </div>
  </div>
  <?php if (empty($landlord_alerts)): ?>
    <p style="color:#9ec3d9;">No offline or late meters detected for your portfolio in the last 24 hours.</p>
  <?php else: ?>
    <table id="alertsTable">
      <thead>
        <tr>
          <th>Type</th>
          <th>Meter</th>
          <th>Property</th>
          <th>Last Sync</th>
          <th>Age</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($landlord_alerts as $a): ?>
          <?php
            $status = $a['status'] ?? 'late';
            $badgeClass = ($status === 'offline') ? 'alert-red' : 'alert-yellow';
          ?>
          <tr data-type="<?= esc($a['type']) ?>" data-tenant-id="<?= (int)($a['tenant_id'] ?? 0) ?>">
            <td>
              <?php
                $t = strtoupper((string)$a['type']);
                if ($t === 'IAMMETER') echo '[IAM]';
                elseif ($t === 'FLECTO') echo '[FLE]';
                elseif ($t === 'WATER') echo '[WTR]';
                else echo '[SYS]';
              ?>
              <?= esc($a['type']) ?>
            </td>
            <td><?= esc($a['meter']) ?></td>
            <td><?= esc($a['property']) ?></td>
            <td><?= esc($a['time']) ?></td>
            <td><?= esc($a['ago']) ?></td>
            <td><span class="alert-badge <?= $badgeClass ?>"><?= esc($status) ?></span></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</div>

<div class="card">
  <h2>Landlord Profile</h2>
  <div class="profile-grid">
    <div class="profile-box">
      <div class="profile-field"><span class="label">Full Name</span><span class="value"><?= esc($landlord_profile['fullname'] ?? '') ?></span></div>
      <div class="profile-field"><span class="label">Email</span><span class="value"><?= esc($landlord_profile['email'] ?? '') ?></span></div>
      <div class="profile-field"><span class="label">Phone</span><span class="value"><?= esc($landlord_profile['phone'] ?? '') ?></span></div>
    </div>

    <div class="profile-box">
      <h3>Flecto Meter Controls</h3>

      <div class="meter-select-wrap">
        <label for="flectoMeterSelect">Select meter</label>
        <select id="flectoMeterSelect" class="inp">
          <option value="">Choose a Flecto meter...</option>
          <?php if (!empty($flecto_control_meters)): ?>
            <?php foreach ($flecto_control_meters as $sn): ?>
              <option value="<?= esc($sn) ?>"><?= esc($sn) ?></option>
            <?php endforeach; ?>
          <?php else: ?>
            <option value="" disabled>No Flecto meters found for this landlord</option>
          <?php endif; ?>
        </select>
      </div>

      <div class="control-row">
        <button type="button" class="btn-outline" id="btnCheckStatus">Check Status</button>

        <button
          type="button"
          class="toggle-btn off"
          id="btnFlectoToggle"
          data-state="off"
          disabled
          title="Select a meter first"
        >
          OFF
        </button>
      </div>

      <div id="flectoStatusText" class="toggle-meta"></div>

      <div class="toggle-meta">
        These buttons are for Flecto Sense smart electricity meters only. Currently in BETA testing.
      </div>
    </div>
  </div>
</div>

<div class="card">
  <h2>Tenant Metrics Summary</h2>
  <div class="search-row" style="margin-bottom:8px;">
    <input id="tenantSearch" class="inp" placeholder="Search tenants..." />
  </div>
  <div style="overflow-x:auto;">
    <table id="tenantTable">
      <thead>
        <tr>
          <th>Tenant</th>
          <th>IAMMETER</th>
          <th>FLECTO</th>
          <th>Water</th>
          <th>Energy Today</th>
          <th>Energy Month</th>
          <th>kVA Today</th>
          <th>Water Today</th>
          <th>Est. Bill</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($tenants as $t): $tid=(int)$t['tenant_id']; ?>
        <?php
          $iam = getIAMMeterData($conn_rbe, $tid);
          $wat = getWaterData($conn_rbe, $tid);
          $todayStart = date('Y-m-d 00:00:00');
          $todayEnd   = date('Y-m-d 23:59:59');
          $touEnabled = false; // TODO: wire real TOU flag
          $flectoSplit = getFlectoEnergySplit($conn_rbe, $tid, $todayStart, $todayEnd, $touEnabled);

          $grid_kwh  = max(0.0, ($iam['energy_today_kwh'] ?? 0) + ($flectoSplit['grid_kwh'] ?? 0));
          $gen_kwh   = max(0.0, $flectoSplit['gen_kwh'] ?? 0);
          $solar_kwh = max(0.0, $flectoSplit['solar_kwh'] ?? 0);
          $energy_today = $grid_kwh + $gen_kwh;
          $kva_now = (float)($iam['kva_now'] ?? 0);

          $grid_cost = $tiers_electricity ? calculate_tiered_cost($grid_kwh, $tiers_electricity) : 0.0;
          $gen_cost  = $tiers_generator   ? calculate_tiered_cost($gen_kwh,  $tiers_generator)   : 0.0;

          $summary = getBillingSummary(
            $conn_rbe,
            (int)$landlord_id,
            $tid,
            $energy_today,
            (float)($wat['water_today_kl'] ?? 0),
            $tiers_electricity,
            $tiers_water,
            $grid_cost + $gen_cost
          );
        ?>
        <tr>
          <td style="font-weight:600; color:#7ed957; text-align:left;"><?= esc($t['fullname']) ?></td>
          <td><?= (int)($tenant_iammeters[$tid] ?? 0) ?></td>
          <td><?= (int)($tenant_flecto_meters[$tid] ?? 0) ?></td>
          <td><?= (int)($tenant_water_meters[$tid] ?? 0) ?></td>
          <td>
            <?= number_format($energy_today, 3) ?> kWh
            <br>
            <small style="color:#9ec3d9;">
              Grid <?= number_format($grid_kwh, 3) ?> /
              Gen <?= number_format($gen_kwh, 3) ?> /
              Solar <?= number_format($solar_kwh, 3) ?> exp
            </small>
          </td>
          <td>-</td>
          <td><?= number_format($kva_now, 2) ?> kVA</td>
          <td><?= number_format((float)($wat['water_today_kl'] ?? 0), 3) ?> kL</td>
          <td>R <?= number_format((float)$summary['total'], 2) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="card">
  <h2>Properties & Meters</h2>
  <?php foreach ($properties as $p): ?>
    <div class="property-section">
      <h3><?= esc($p['property_number']) ?> - <?= esc($p['address']) ?></h3>
      <button class="view-address-btn" data-address="<?= esc($p['address']) ?>">View Address</button>
    </div>
  <?php endforeach; ?>
</div>

<div id="addressModal" class="modal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.7);">
  <div class="modal-content">
    <span id="closeModal" class="close">&times;</span>
    <p id="addressText"></p>
  </div>
</div>

<script>
  const modal = document.getElementById('addressModal');
  const text = document.getElementById('addressText');
  const closeBtn = document.getElementById('closeModal');

  document.querySelectorAll('.view-address-btn').forEach(btn => {
    btn.addEventListener('click', () => { text.textContent = btn.dataset.address; modal.style.display='flex'; });
  });
  closeBtn.addEventListener('click', () => { modal.style.display='none'; });
  window.addEventListener('click', (e) => { if (e.target === modal) modal.style.display='none'; });

  // Simple client-side tenant search
  const search = document.getElementById('tenantSearch');
  const tenantTable = document.getElementById('tenantTable');
  if (search && tenantTable) {
    search.addEventListener('input', () => {
      const q = search.value.toLowerCase();
      tenantTable.querySelectorAll('tbody tr').forEach(tr => {
        const name = (tr.cells[0].innerText || '').toLowerCase();
        tr.style.display = name.includes(q) ? '' : 'none';
      });
    });
  }

  const alertFilter = document.getElementById('alertTypeFilter');
  const alertsTable = document.getElementById('alertsTable');
  if (alertFilter && alertsTable) {
    alertFilter.addEventListener('change', () => {
      const type = alertFilter.value;
      alertsTable.querySelectorAll('tbody tr').forEach(tr => {
        const t = (tr.getAttribute('data-type') || '').toUpperCase();
        tr.style.display = (type === 'ALL' || t === type) ? '' : 'none';
      });
    });
  }

  if (alertsTable) {
    alertsTable.querySelectorAll('tbody tr').forEach(tr => {
      tr.addEventListener('click', () => {
        const tenantId = tr.getAttribute('data-tenant-id');
        if (tenantId && tenantId !== '0') {
          window.location.href = 'tenant-dashboard.php?tenant_id=' + encodeURIComponent(tenantId);
        }
      });
    });
  }

  // Flecto Controls (wired)
  const btnCheckStatus = document.getElementById('btnCheckStatus');
  const btnFlectoToggle = document.getElementById('btnFlectoToggle');
  const flectoMeterSelect = document.getElementById('flectoMeterSelect');
  const flectoStatusText = document.getElementById('flectoStatusText');

  let lastStatusPollAt = 0;

  function selectedMeter() {
    return (flectoMeterSelect && flectoMeterSelect.value) ? flectoMeterSelect.value : '';
  }

  function setStatusText(msg) {
    if (flectoStatusText) flectoStatusText.textContent = msg || '';
  }

  function setToggleVisual(isOn) {
    if (!btnFlectoToggle) return;
    const next = isOn ? 'on' : 'off';
    btnFlectoToggle.setAttribute('data-state', next);
    btnFlectoToggle.classList.remove('on', 'off');
    btnFlectoToggle.classList.add(next);
    btnFlectoToggle.textContent = next.toUpperCase();
  }

  async function flectoCall(command, serial) {
    const res = await fetch('/api/flecto/control.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ command, serial })
    });

    const json = await res.json().catch(() => null);
    if (!res.ok || !json) {
      throw new Error((json && json.error) ? json.error : ('Request failed (' + res.status + ')'));
    }
    return json;
  }

  function parseSwitchState(flectoPayload) {
    const f = flectoPayload || {};
    const data = f.meter_data || f.meterData || {};
    const sw = data.switch;

    if (sw === 4 || sw === '4') return true;
    if (sw === 1 || sw === '1') return false;

    const st = (f.state || '').toLowerCase();
    if (st === 'connected') return true;
    if (st === 'disconnected') return false;

    return null;
  }

  async function doStatus(serial) {
    const now = Date.now();
    if (now - lastStatusPollAt < 10000) {
      const secs = Math.ceil((10000 - (now - lastStatusPollAt)) / 1000);
      setStatusText('Rate limit protection: try again in ' + secs + 's.');
      return;
    }
    lastStatusPollAt = now;

    setStatusText('Checking status for ' + serial + ' ...');
    const r = await flectoCall('status', serial);
    const f = r.flecto || {};
    const isOn = parseSwitchState(f);

    if (isOn === true) {
      setToggleVisual(true);
      setStatusText('Meter is ON (connected).');
    } else if (isOn === false) {
      setToggleVisual(false);
      setStatusText('Meter is OFF (disconnected).');
    } else {
      setStatusText('Status received, but switch state was unclear.');
    }

    if ((f.state || '').toLowerCase() === 'ct_meter') {
      if (btnFlectoToggle) btnFlectoToggle.disabled = true;
      setStatusText('This is a CT meter and cannot be switched.');
    }

    return r;
  }

  if (flectoMeterSelect && btnFlectoToggle) {
    flectoMeterSelect.addEventListener('change', async () => {
      const serial = selectedMeter();
      const hasMeter = !!serial;

      btnFlectoToggle.disabled = !hasMeter;
      btnFlectoToggle.title = hasMeter ? '' : 'Select a meter first';

      if (hasMeter) {
        try { await doStatus(serial); } catch (e) { setStatusText(String(e.message || e)); }
      } else {
        setStatusText('');
      }
    });
  }

  if (btnCheckStatus) {
    btnCheckStatus.addEventListener('click', async () => {
      const serial = selectedMeter();
      if (!serial) { alert('Please select a Flecto meter first.'); return; }
      try { await doStatus(serial); } catch (e) { setStatusText(String(e.message || e)); }
    });
  }

  if (btnFlectoToggle) {
    btnFlectoToggle.addEventListener('click', async () => {
      const serial = selectedMeter();
      if (!serial) { alert('Please select a Flecto meter first.'); return; }

      const current = (btnFlectoToggle.getAttribute('data-state') || 'off').toLowerCase();
      const nextCommand = (current === 'on') ? 'disconnect' : 'connect';

      setStatusText('Sending ' + nextCommand.toUpperCase() + ' to ' + serial + ' ...');

      try {
        await flectoCall(nextCommand, serial);

        setTimeout(async () => {
          try { await doStatus(serial); } catch (e) { setStatusText(String(e.message || e)); }
        }, 3000);

      } catch (e) {
        setStatusText(String(e.message || e));
      }
    });
  }
</script>

</body>
</html>