<?php
// FINAL Landlord Dashboard â€“ Fully Fixed
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'db_connect.php';

// --- Access Control ---
$role = null;
if (isset($_GET['landlord_id']) && isset($_SESSION['user_id'])) {

    $admin_id = $_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 = intval($_GET['landlord_id']);
    } else {
        exit('Access denied.');
    }
} elseif (isset($_SESSION['user_id'])) {
    $landlord_id = $_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();
}

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

$stmt = $conn_rbe->prepare("SELECT use_wallet FROM rbe_users WHERE id = ?");
$stmt->execute([$landlord_id]);
$use_wallet = (int)$stmt->fetchColumn();

// --- Tenant Data ---
$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);

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

// --- Billing Settings ---
$stmt = $conn_rbe->prepare("SELECT * FROM billing_settings WHERE landlord_id = ? LIMIT 1");
$stmt->execute([$landlord_id]);
$billing = $stmt->fetch(PDO::FETCH_ASSOC) ?: [
    'sell_rate' => 0,
    'buy_rate' => 0,
    'other_fees' => 0,
    'kva_cost' => 0,
    'kva_sell' => 0
];

// --- Helper Function ---
function calculate_flecto_total_kwh($row) {
    return floatval($row['reg_a'] ?? 0) + floatval($row['reg_e'] ?? 0) + floatval($row['reg_f'] ?? 0) + floatval($row['reg_g'] ?? 0) + floatval($row['reg_h'] ?? 0) + floatval($row['reg_l'] ?? 0);
}
function calculate_flecto_kvah_today($first_reading, $last_reading) {
    // Active Energy (kWh)
    $active_first = floatval($first_reading['reg_a'] ?? 0) + floatval($first_reading['reg_h'] ?? 0) + floatval($first_reading['reg_l'] ?? 0);
    $active_last  = floatval($last_reading['reg_a'] ?? 0) + floatval($last_reading['reg_h'] ?? 0) + floatval($last_reading['reg_l'] ?? 0);
    $active_diff  = max(0, $active_last - $active_first);

    // Reactive Energy (kvarh)
    $reactive_first = floatval($first_reading['reg_c'] ?? 0) + floatval($first_reading['reg_j'] ?? 0) + floatval($first_reading['reg_n'] ?? 0);
    $reactive_last  = floatval($last_reading['reg_c'] ?? 0) + floatval($last_reading['reg_j'] ?? 0) + floatval($last_reading['reg_n'] ?? 0);
    $reactive_diff  = max(0, $reactive_last - $reactive_first);

    // Apparent Energy (kVAh)
    return sqrt(pow($active_diff, 2) + pow($reactive_diff, 2));
}


$today = date('Y-m-d');
$start_today = "$today 00:00:00";
$end_today = "$today 23:59:59";
$start_month = date('Y-m-01 00:00:00');

$tenant_power_now = [];
$tenant_energy_today = [];
$tenant_kva_today = [];
$tenant_water_today = [];
$tenant_water_month = [];
$tenant_energy_month = [];
$tenant_iammeters = [];
$tenant_flecto_meters = [];
$tenant_water_meters = [];
$property_details = [];

foreach ($tenants as $tenant) {
    $tid = $tenant['tenant_id'];

    $stmt = $conn_rbe->prepare("SELECT id FROM smart_meters WHERE tenant_id = ? AND source_type = 'IAMMETER'");
    $stmt->execute([$tid]);
    $smart_meters = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $tenant_iammeters[$tid] = count($smart_meters);

    $stmt = $conn_rbe->prepare("SELECT serial_number FROM flecto_meters WHERE tenant_id = ?");
    $stmt->execute([$tid]);
    $flecto_serials = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $tenant_flecto_meters[$tid] = count($flecto_serials);

    $stmt = $conn_rbe->prepare("SELECT serial_number FROM water_meters WHERE tenant_id = ?");
    $stmt->execute([$tid]);
    $water_serials = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $tenant_water_meters[$tid] = count($water_serials);

    $power_now = 0;
    $energy_today = 0;
    $kva_today = 0;
    $energy_month_iam = 0;
    $energy_month_flecto = 0;
    $water_today = 0;
    $water_month = 0;

    foreach ($smart_meters as $meter_id) {
        $stmt = $conn_rbe->prepare("SELECT reading_timestamp FROM smart_meter_readings WHERE meter_id = ? AND reading_timestamp BETWEEN ? AND ? GROUP BY reading_timestamp HAVING COUNT(DISTINCT phase) = 3 ORDER BY reading_timestamp ASC");
        $stmt->execute([$meter_id, $start_today, $end_today]);
        $timestamps = $stmt->fetchAll(PDO::FETCH_COLUMN);

        if (count($timestamps) >= 2) {
            $first_ts = $timestamps[0];
            $last_ts  = end($timestamps);

            $stmt = $conn_rbe->prepare("SELECT reading_timestamp, energy_total FROM smart_meter_readings WHERE meter_id = ? AND reading_timestamp IN (?, ?)");
            $stmt->execute([$meter_id, $first_ts, $last_ts]);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $sums = [$first_ts => 0, $last_ts => 0];
            foreach ($rows as $r) {
                $sums[$r['reading_timestamp']] += floatval($r['energy_total']);
            }

            $diff_wh = max(0, $sums[$last_ts] - $sums[$first_ts]);
            $energy_today += $diff_wh;

            $stmt = $conn_rbe->prepare("SELECT power FROM smart_meter_readings WHERE meter_id = ? AND reading_timestamp = ? ORDER BY phase DESC LIMIT 1");
            $stmt->execute([$meter_id, $last_ts]);
            $power_now += floatval($stmt->fetchColumn());

            $stmt = $conn_rbe->prepare("SELECT voltage, current FROM smart_meter_readings WHERE meter_id = ? AND reading_timestamp = ? ORDER BY phase DESC LIMIT 1");
            $stmt->execute([$meter_id, $last_ts]);
            if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $kva_today += floatval($row['voltage']) * floatval($row['current']) / 1000;
            }
        }

        $stmt = $conn_rbe->prepare("SELECT reading_timestamp FROM smart_meter_readings WHERE meter_id = ? AND reading_timestamp BETWEEN ? AND ? GROUP BY reading_timestamp HAVING COUNT(DISTINCT phase) = 3 ORDER BY reading_timestamp ASC");
        $stmt->execute([$meter_id, $start_month, $end_today]);
        $timestamps_month = $stmt->fetchAll(PDO::FETCH_COLUMN);

        if (count($timestamps_month) >= 2) {
            $first_ts_month = $timestamps_month[0];
            $last_ts_month  = end($timestamps_month);

            $stmt = $conn_rbe->prepare("SELECT reading_timestamp, energy_total FROM smart_meter_readings WHERE meter_id = ? AND reading_timestamp IN (?, ?)");
            $stmt->execute([$meter_id, $first_ts_month, $last_ts_month]);
            $rows_month = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $sums_month = [$first_ts_month => 0, $last_ts_month => 0];
            foreach ($rows_month as $r) {
                $sums_month[$r['reading_timestamp']] += floatval($r['energy_total']);
            }

            $diff_wh_month = max(0, $sums_month[$last_ts_month] - $sums_month[$first_ts_month]);
            $energy_month_iam += $diff_wh_month;
        }
    }
$kvah_today_total = 0;
    foreach ($flecto_serials as $serial) {
        $stmt = $conn_rbe->prepare("SELECT * FROM flecto_meter_readings WHERE serial = ? AND created_at BETWEEN ? AND ? ORDER BY created_at ASC");
        $stmt->execute([$serial, $start_today, $end_today]);
        $rows_today = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (count($rows_today) >= 2) {
            $first = $rows_today[0];
            $last = end($rows_today);
            $sum_first = calculate_flecto_total_kwh($first);
            $sum_last = calculate_flecto_total_kwh($last);
            $energy_today += max(0, $sum_last - $sum_first);
            $kvah_today_total += calculate_flecto_kvah_today($first, $last);
        }

        $stmt = $conn_rbe->prepare("SELECT * FROM flecto_meter_readings WHERE serial = ? AND created_at BETWEEN ? AND ? ORDER BY created_at ASC");
        $stmt->execute([$serial, $start_month, $end_today]);
        $rows_month = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (count($rows_month) >= 2) {
            $first_month = $rows_month[0];
            $last_month = end($rows_month);
            $sum_first_month = calculate_flecto_total_kwh($first_month);
            $sum_last_month = calculate_flecto_total_kwh($last_month);
            $energy_month_flecto += max(0, $sum_last_month - $sum_first_month);
        }
    }

    foreach ($water_serials as $serial) {
        $stmt = $conn_rbe->prepare("SELECT MIN(volume_liters), MAX(volume_liters) FROM water_meter_readings WHERE serial_number = ? AND reading_datetime BETWEEN ? AND ?");
        $stmt->execute([$serial, $start_today, $end_today]);
        [$min_today, $max_today] = $stmt->fetch(PDO::FETCH_NUM);
        $water_today += max(0, floatval($max_today) - floatval($min_today));

        $stmt = $conn_rbe->prepare("SELECT MIN(volume_liters), MAX(volume_liters) FROM water_meter_readings WHERE serial_number = ? AND reading_datetime BETWEEN ? AND ?");
        $stmt->execute([$serial, $start_month, $end_today]);
        [$min_month, $max_month] = $stmt->fetch(PDO::FETCH_NUM);
        $water_month += max(0, floatval($max_month) - floatval($min_month));
    }

    $tenant_energy_today[$tid] = round($energy_today / 1000, 2);
    $tenant_energy_month[$tid] = round(($energy_month_iam + $energy_month_flecto) / 1000, 2);
    $tenant_power_now[$tid] = round($power_now, 2);
    $tenant_kvah_today[$tid] = round($kvah_today_total, 2);
    $tenant_kva_today[$tid] = round($kva_today, 2);
    $tenant_water_today[$tid] = round($water_today / 1000, 2);
    $tenant_water_month[$tid] = round($water_month / 1000, 2);

    // Save metrics (energy_today, energy_month, power_now, kva_today placeholders for now)
//    $tenant_energy_today[$tid] = $energy_today;
//    $tenant_energy_month[$tid] = $energy_month_iam + $energy_month_flecto;
//    $tenant_power_now[$tid] = $power_now;
//    $tenant_kva_today[$tid] = $kva_today;
}

foreach ($properties as $property) {
    $pid = $property['id'];
    $iammeters = [];
    $flectos = [];

    // IAMMETER meters
    $iam_stmt = $conn_rbe->prepare("SELECT * FROM smart_meters WHERE property_id = ? AND landlord_id = ? AND source_type = 'IAMMETER'");
    $iam_stmt->execute([$pid, $landlord_id]);
    $iammeters = $iam_stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($iammeters as &$m) {
        $stmt = $conn_rbe->prepare("SELECT power FROM smart_meter_readings WHERE meter_id = ? ORDER BY reading_timestamp DESC LIMIT 1");
        $stmt->execute([$m['id']]);
        $m['latest_power'] = $stmt->fetchColumn();
        $m['serial'] = isset($m['serial']) && trim($m['serial']) !== '' ? $m['serial'] : null;
    }
    unset($m);

    // FLECTO meters
    $flecto_stmt = $conn_rbe->prepare("SELECT * FROM flecto_meters WHERE property_id = ? AND landlord_id = ?");
    $flecto_stmt->execute([$pid, $landlord_id]);
    $flectos_temp = $flecto_stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($flectos_temp as $m) {
        $serial = $m['serial'] ?? $m['serial_number'] ?? null;
        if ($serial) {
            $stmt = $conn_rbe->prepare("SELECT * FROM flecto_meter_readings WHERE serial = ? ORDER BY created_at DESC LIMIT 1");
            $stmt->execute([$serial]);
            $latest_row = $stmt->fetch(PDO::FETCH_ASSOC);
            $m['latest_energy'] = $latest_row ? calculate_flecto_total_kwh($latest_row) : null;
            $m['display_serial'] = $serial;
        }
        $flectos[] = $m;
    }

    // Water meters
    $waters_stmt = $conn_rbe->prepare("SELECT * FROM water_meters WHERE property_id = ? AND landlord_id = ?");
    $waters_stmt->execute([$pid, $landlord_id]);
    $waters = $waters_stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($waters as &$m) {
        $stmt = $conn_rbe->prepare("SELECT volume_liters FROM water_meter_readings WHERE serial_number = ? AND volume_liters IS NOT NULL ORDER BY reading_datetime DESC LIMIT 1");
        $stmt->execute([$m['serial_number']]);
        $latest_volume = $stmt->fetchColumn();
        $m['latest_water'] = $latest_volume !== false ? round($latest_volume / 1000, 2) : null;
    }
    unset($m);

    $property_details[] = [
        'property'   => $property,
        'iammeters'  => $iammeters,
        'flectos'    => $flectos,
        'waters'     => $waters
    ];
}


?>



<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Landlord Dashboard â€“ RBE</title>
  <style>
  body {
    font-family: Arial, sans-serif;
    background: #051a25;
    color: #ffffff;
    margin: 0;
    padding: 20px;
  }

  h1, h2, h3 {
    color: #7ed957;
    margin-top: 0;
  }

  /* Navigation Buttons */
  .nav-btn {
    background: #7ed957;
    color: #000;
    padding: 10px 20px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: bold;
    display: inline-block;
    margin-bottom: 20px;
  }

  .nav {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 15px;
    margin: 0 auto 30px auto;
    max-width: 1000px;
  }

  .nav a {
    background: #7ed957;
    color: #000;
    padding: 15px 25px;
    border-radius: 12px;
    text-decoration: none;
    font-weight: bold;
    flex: 1 1 160px;
    box-shadow: 0 3px 8px rgba(0,0,0,0.4);
    transition: background 0.3s ease, transform 0.2s ease;
  }

  .nav a:hover {
    background: #00cc77;
    transform: translateY(-2px);
  }

  /* Section Titles */
  .section-title {
    font-size: 1.8em;
    margin-bottom: 20px;
    color: #7ed957;
    border-bottom: 2px solid #1b3a4d;
    padding-bottom: 6px;
  }

  /* Profile Layout */
  .profile-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 30px;
    margin-top: 20px;
  }

  .profile-box {
    background-color: #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: bold;
    color: #7ed957;
    margin-bottom: 6px;
    font-size: 1.1em;
  }

  .profile-field .value {
    color: #ffffff;
    font-size: 1.1em;
    line-height: 1.5;
  }

  .list-unstyled {
    list-style: none;
    padding-left: 0;
    margin: 0;
  }

  .list-style {
    padding-left: 20px;
    margin: 10px 0 0 0;
    list-style-type: disc;
    color: #ffffff;
    font-size: 1.05em;
  }

  /* Properties & Meters Section */
  .property-section {
    background: #122c4c;
    padding: 20px;
    border-radius: 12px;
    margin-top: 30px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  }

  .meter-group {
    margin-top: 15px;
  }

  .meter-group h4 {
    color: #00ccff;
    margin-bottom: 8px;
  }

  ul.meter-list {
    list-style: none;
    padding: 0;
  }

  ul.meter-list li {
    padding: 8px;
    border-bottom: 1px solid #1b3a4d;
  }

  /* Data Tables */
  table {
    width: 100%;
    border-collapse: collapse;
    background: #0b1f33;
    color: #fff;
    margin-top: 20px;
    font-size: 0.95em;
  }

  th, td {
    padding: 12px;
    text-align: center;
    border: 1px solid #7ed957;
  }

  th {
    background-color: #1b3a4d;
    color: #7ed957;
    font-weight: bold;
  }

  tr:hover {
    background-color: #1a2a3a;
  }

  /* Modal Popup */
  .modal {
  position: fixed;
  inset: 0; /* shorthand for top: 0; right: 0; bottom: 0; left: 0 */
  background-color: rgba(0, 0, 0, 0.7);
  display: none; /* start hidden */
  justify-content: center;
  align-items: center;
}
.modal.show {
  display: flex !important; /* override inline display:none */
}


  .modal-content {
    background: #0b1f33;
    padding: 20px 30px;
    border-radius: 12px;
    color: #fff;
    max-width: 500px;
    width: 90%;
    position: relative;
    box-shadow: 0 6px 20px rgba(0,0,0,0.5);
    animation: fadeIn 0.25s ease-out;
  }

  .modal .close {
    color: #7ed957;
    position: absolute;
    top: 12px;
    right: 16px;
    font-size: 24px;
    cursor: pointer;
  }

  /* View Address Button */
  .view-address-btn {
    background-color: #7ed957;
    color: #000;
    border: none;
    padding: 5px 10px;
    border-radius: 6px;
    font-size: 0.85em;
    cursor: pointer;
    margin-left: 10px;
    transition: background 0.2s ease;
  }

  .view-address-btn:hover {
    background-color: #66c24e;
  }

  /* Animation */
  @keyframes fadeIn {
    from {
      transform: scale(0.95);
      opacity: 0;
    }
    to {
      transform: scale(1);
      opacity: 1;
    }
  }
  
  /* Tenant Metrics Styling */
.tenant-metrics {
  margin-top: 35px;
}

.tenant-metrics h2 {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.5rem;
}

.table-wrapper {
  overflow-x: auto;
  border-radius: 10px;
  box-shadow: 0 3px 12px rgba(0,0,0,0.3);
  background: #0b1f33;
  margin-top: 10px;
}

table.metrics {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.9em;
}

table.metrics thead {
  position: sticky;
  top: 0;
  background: #1b3a4d;
}

table.metrics th {
  padding: 10px 8px;
  color: #7ed957;
  font-weight: 700;
  text-align: center;
  border-bottom: 2px solid #122c4c;
}

table.metrics td {
  padding: 8px;
  text-align: right;
  border-bottom: 1px solid #1b3a4d;
}

table.metrics td:first-child {
  text-align: left;
  font-weight: 600;
  color: #7ed957;
  white-space: nowrap;
}

table.metrics tr:nth-child(even) {
  background: #0e2b3f;
}

table.metrics tr:hover {
  background: #19334a;
}

/* Units and numbers */
.metrics .num {
  color: #fff;
}
.metrics .unit {
  color: #7ed957;
  font-size: 0.85em;
  margin-left: 4px;
  opacity: 0.8;
}

/* Responsive collapse */
@media (max-width: 850px) {
  table.metrics th:nth-child(5),
  table.metrics td:nth-child(5),
  table.metrics th:nth-child(6),
  table.metrics td:nth-child(6) {
    display: none; /* hide month data on narrow screens */
  }
}

</style>

</head>
<body>
<?php
$newAppUrl = RBE_V2_BASE_URL;
include __DIR__ . '/includes/new_app_banner.php';
?>

<?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="nav">
  <a href="billing.php?landlord_id=<?= $landlord_id ?>">Billing</a>
  <a href="manage-tenants.php?landlord_id=<?= $landlord_id ?>">Manage Tenants</a>
  <a href="<?= ($role === 'admin') ? 'admin-reports.php' : 'reports.php' ?>">Reports</a>

  <a href="logout.php">Logout</a>
</div>

<h1>ðŸ  Landlord Dashboard</h1>
<h2 class="section-title">ðŸ“‡ Landlord Profile</h2>

<div class="profile-grid">
  <div class="profile-box">
    <div class="profile-field">
      <span class="label">ðŸ‘¤ Full Name</span>
      <span class="value"><?= htmlspecialchars($landlord_profile['fullname']) ?></span>
    </div>
    <div class="profile-field">
      <span class="label">ðŸ“§ Email</span>
      <span class="value"><?= htmlspecialchars($landlord_profile['email']) ?></span>
    </div>
    <div class="profile-field">
      <span class="label">ðŸ“ž Phone</span>
      <span class="value"><?= htmlspecialchars($landlord_profile['phone']) ?></span>
    </div>
  </div>
<div class="profile-box">
  <h3>âš™ï¸ Wallet Settings (Per Tenant)</h3>
  <form method="post" action="wallet/wallet_toggle.php">
    <input type="hidden" name="landlord_id" value="<?= $landlord_id ?>">
    <ul class="value list-unstyled">
      <?php foreach ($tenants as $t): ?>
        <?php
          $stmt = $conn_rbe->prepare("
            SELECT use_wallet 
            FROM tenant_landlord_map 
            WHERE tenant_id = ? AND landlord_id = ?
          ");
          $stmt->execute([$t['tenant_id'], $landlord_id]);
          $use_wallet = (int)$stmt->fetchColumn();
        ?>
        <li>
          <label style="color:#fff;">
            <input type="checkbox" name="tenants[<?= $t['tenant_id'] ?>]" value="1"
              <?= $use_wallet ? 'checked' : '' ?>>
            <?= htmlspecialchars($t['fullname']) ?>
          </label>
        </li>
      <?php endforeach; ?>
    </ul>
    <button type="submit" class="nav-btn" style="margin-top:10px;">Save</button>
  </form>
</div> 

<?php if ($use_wallet): ?>
  <div class="profile-box">
    <h3>ðŸ’° Landlord Wallet</h3>
    <?php
      require_once __DIR__ . "/wallet/includes/wallet_db.php";
      $balance = getLandlordBalance($landlord_id, $conn_rbe);

      // Fetch pending payouts (if you use landlord_wallet_payouts with a status column)
      $stmt = $conn_rbe->prepare("
        SELECT COALESCE(SUM(amount),0) 
        FROM landlord_wallet_payouts 
        WHERE landlord_id = ? AND (status IS NULL OR status = 'pending')
      ");
      $stmt->execute([$landlord_id]);
      $pending_payouts = (float)$stmt->fetchColumn();
    ?>
    <p><strong>Withdrawable Balance:</strong> R <?= number_format($balance, 2) ?></p>

    <?php if ($pending_payouts > 0): ?>
      <p style="color:#ff7777; font-weight:bold;">
        Pending Payouts: R <?= number_format($pending_payouts, 2) ?>
      </p>
    <?php endif; ?>

    <a class="nav-btn" href="wallet/landlord/payouts.php?landlord_id=<?= $landlord_id ?>">Request Payout</a>
    <a class="nav-btn" href="wallet/landlord/history.php?landlord_id=<?= $landlord_id ?>">View Transactions</a>
  </div>
<?php endif; ?>
 

  <div class="profile-box">
    <div class="profile-field">
      <span class="label">ðŸ˜ï¸ Properties</span>
      <ul class="value list-unstyled">
        <?php foreach ($properties as $p): ?>
          <li>
  <?= htmlspecialchars($p['property_number']) ?>
  <button class="view-address-btn" data-address="<?= htmlspecialchars($p['address']) ?>">
    ðŸ“ View Address
  </button>
</li>

        <?php endforeach; ?>
      </ul>
    </div>

    <div class="profile-field">
      <span class="label">ðŸ‘¥ Tenants</span>
      <ul class="value list-unstyled">
        <?php foreach ($tenants as $t): ?>
          <li><?= htmlspecialchars($t['fullname']) ?> <small>(ID: <?= $t['tenant_id'] ?>)</small></li>
        <?php endforeach; ?>
      </ul>
    </div>
  </div>
</div>


<div class="tenant-metrics">
  <h2>ðŸ“Š Tenant Metrics Summary</h2>
  <div class="table-wrapper">
    <table class="metrics">
      <thead>
        <tr>
          <th>ðŸ‘¤ Tenant</th>
          <th>ðŸ”Œ IAM</th>
          <th>âš¡ FLECTO</th>
          <th>ðŸš¿ WATER</th>
          <th>ðŸ”‹ Energy Today</th>
          <th>ðŸ”‹ Energy Month</th>
          <th>âš¡ kVA Today</th>
          <th>ðŸš¿ Water Today</th>
          <th>ðŸš¿ Water Month</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($tenants as $tenant): 
            $tid = $tenant['tenant_id'];
            $name = htmlspecialchars($tenant['fullname']);
            $display_kva_today = $tenant_kva_today[$tid] ?? 0;
            if (($tenant_iammeters[$tid] ?? 0) == 0 && ($tenant_flecto_meters[$tid] ?? 0) > 0) {
              $display_kva_today = $tenant_kvah_today[$tid] ?? 0;
            }
        ?>
        <tr>
          <td><?= $name ?></td>
          <td><?= $tenant_iammeters[$tid] ?? 0 ?></td>
          <td><?= $tenant_flecto_meters[$tid] ?? 0 ?></td>
          <td><?= $tenant_water_meters[$tid] ?? 0 ?></td>

          <td><span class="num"><?= number_format($tenant_energy_today[$tid] ?? 0, 2) ?></span><span class="unit"> kWh</span></td>
          <td><span class="num"><?= number_format($tenant_energy_month[$tid] ?? 0, 2) ?></span><span class="unit"> kWh</span></td>
          <td><span class="num"><?= number_format($display_kva_today, 2) ?></span><span class="unit"> kVA</span></td>
          <td><span class="num"><?= number_format($tenant_water_today[$tid] ?? 0, 2) ?></span><span class="unit"> kl</span></td>
          <td><span class="num"><?= number_format($tenant_water_month[$tid] ?? 0, 2) ?></span><span class="unit"> kl</span></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>




<h2>ðŸ“‹ Properties & Meters</h2>
<?php foreach ($property_details as $group): ?>
<div class="property-section">
  <h3>ðŸ¨ <?= htmlspecialchars($group['property']['property_number']) ?> â€” <?= htmlspecialchars($group['property']['address']) ?></h3>

  <?php if (!empty($group['iammeters'])): ?>
  <div class="meter-group">
    <h4>ðŸ”Œ IAMMETER Meters</h4>
    <ul class="meter-list">
      <?php foreach ($group['iammeters'] as $m): ?>
        <li>
          <?= $role === 'admin' ? '<a href="reassign_meter.php?id=' . $m['id'] . '" style="color:#7ed957; text-decoration:none;">' : '' ?>
          <strong>Serial:</strong>
<?= isset($m['serial']) && trim($m['serial']) !== '' ? htmlspecialchars($m['serial']) : '<em style="color:#ccc;">Unassigned</em>' ?>

          <?= !empty($m['phases']) ? ' â€” ' . htmlspecialchars($m['phases']) . ' phase' : '' ?>
          <?= $role === 'admin' ? '</a>' : '' ?>
          <br><small>ðŸ”‹ Power Now: <?= isset($m['latest_power']) ? number_format($m['latest_power'], 1) . ' W' : 'n/a' ?></small>
        </li>
      <?php endforeach; ?>
    </ul>
  </div>
  <?php endif; ?>

  <?php if (!empty($group['flectos'])): ?>
  <div class="meter-group">
    <h4>âš¡ FLECTO Meters</h4>
    <ul class="meter-list">
      <?php foreach ($group['flectos'] as $m): ?>
        <li>
          <?= $role === 'admin' ? '<a href="reassign_flecto_meter.php?id=' . $m['id'] . '" style="color:#7ed957; text-decoration:none;">' : '' ?>
          <strong>Serial:</strong> <?= htmlspecialchars($m['display_serial'] ?? 'n/a') ?>
          <?= $role === 'admin' ? '</a>' : '' ?>
          <br><small>âš¡ Latest Reading: <?= isset($m['latest_energy']) ? number_format($m['latest_energy'], 2) . ' kWh' : 'n/a' ?></small>
        </li>
      <?php endforeach; ?>
    </ul>
  </div>
  <?php endif; ?>

  <?php if (!empty($group['waters'])): ?>
  <div class="meter-group">
    <h4>ðŸš° Water Meters</h4>
    <ul class="meter-list">
      <?php foreach ($group['waters'] as $m): ?>
        <li>
          <?= $role === 'admin' ? '<a href="reassign_water_meter.php?id=' . $m['id'] . '" style="color:#7ed957; text-decoration:none;">' : '' ?>
          <strong>Serial:</strong> <?= htmlspecialchars($m['serial_number'] ?? 'n/a') ?>
          <?= $role === 'admin' ? '</a>' : '' ?>
          <br><small>ðŸš° Latest Reading: <?= isset($m['latest_water']) ? number_format($m['latest_water'], 2) . ' kl' : 'n/a' ?></small>
        </li>
      <?php endforeach; ?>
    </ul>
  </div>
  <?php endif; ?>

</div>
<?php endforeach; ?>
<div id="addressModal" class="modal" style="display:none;">
  <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');

  // Attach click event to all "View Address" buttons
  document.querySelectorAll('.view-address-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      text.textContent = btn.dataset.address;
      modal.classList.add('show'); // Add class to show modal
    });
  });

  // Close modal on close button click
  closeBtn.addEventListener('click', () => {
    modal.classList.remove('show');
  });

  // Close modal when clicking outside the modal content
  window.addEventListener('click', (e) => {
    if (e.target === modal) {
      modal.classList.remove('show');
    }
  });

  // Optional: close modal on Escape key
  window.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      modal.classList.remove('show');
    }
  });
</script>


</body>
</html>



