<?php
// manage-tenants.php — RBE Utilities
// Tenants list + drawer editor with versioned billing + extra fee toggles

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__ . '/modules/billing/includes/energy_engine.php';

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

// Access control and landlord scoping
$stmt = $conn_rbe->prepare('SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1');
$stmt->execute([$user_id]);
$role = $stmt->fetchColumn();
if (!in_array($role, ['admin','landlord'], true)) { exit('Access denied.'); }
$is_admin = ($role === 'admin');
$landlord_id = $is_admin ? (int)($_GET['landlord_id'] ?? 0) : $user_id;

// Sidebar navigation (admin vs landlord)
if ($is_admin) {
  include 'admin-nav.php';
} else {
  include 'landlord-nav.php';
}

// Helpers
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; } }
function has_column(PDO $pdo, string $table, string $col): bool { try { $q=$pdo->prepare("SHOW COLUMNS FROM `{$table}` LIKE ?"); $q->execute([$col]); return (bool)$q->fetch(PDO::FETCH_ASSOC);} catch(Throwable $e){ return false; } }
function next_cycle_first_day(): string { $d=new DateTime('first day of next month'); return $d->format('Y-m-d'); }

// Feature flags
$has_effective_from = has_column($conn_rbe, 'billing_settings', 'effective_from');
$has_effective_to   = has_column($conn_rbe, 'billing_settings', 'effective_to');
$has_history_table  = has_table($conn_rbe, 'billing_settings_history');
$has_extra_fees     = has_table($conn_rbe, 'extra_fees');

// Create tenant (minimal happy path)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_tenant'])) {
  $fullname = trim((string)($_POST['fullname'] ?? ''));
  $email    = trim((string)($_POST['email'] ?? ''));
  $phone    = trim((string)($_POST['phone'] ?? ''));
  $owner_id = $is_admin ? (int)($_POST['landlord_id'] ?? 0) : $user_id;
  if ($fullname !== '' && $email !== '' && $owner_id > 0) {
    $stmt = $conn_rbe->prepare('SELECT id FROM rbe_users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    $new_user_id = (int)($stmt->fetchColumn() ?: 0);
    if ($new_user_id > 0) {
      $stmt = $conn_rbe->prepare('UPDATE rbe_users SET fullname=?, phone=?, is_active=1, is_deleted=0 WHERE id=?');
      $stmt->execute([$fullname, $phone, $new_user_id]);
    } else {
      $stmt = $conn_rbe->prepare('INSERT INTO rbe_users (fullname, email, phone, must_set_password, is_active, is_deleted) VALUES (?, ?, ?, 1, 1, 0)');
      $stmt->execute([$fullname, $email, $phone]);
      $new_user_id = (int)$conn_rbe->lastInsertId();
    }
    $stmt = $conn_rbe->prepare('INSERT IGNORE INTO rbe_roles (user_id, role) VALUES (?, "tenant")');
    $stmt->execute([$new_user_id]);
    $stmt = $conn_rbe->prepare('INSERT INTO tenant_landlord_map (tenant_id, landlord_id) VALUES (?, ?)');
    $stmt->execute([$new_user_id, $owner_id]);
    $message = 'New tenant added.';
  } else { $message = 'Full name, email, and landlord are required.'; }
}

// Delete tenant from standalone RBE account data
if (isset($_GET['delete']) && ctype_digit((string)$_GET['delete'])) {
  $delete_id = (int)$_GET['delete'];
  if (!$is_admin) {
    $chk = $conn_rbe->prepare('SELECT 1 FROM tenant_landlord_map WHERE tenant_id = ? AND landlord_id = ?');
    $chk->execute([$delete_id, $landlord_id]);
    if (!$chk->fetchColumn()) exit('Access denied.');
  }
  $conn_rbe->prepare('DELETE FROM tenant_landlord_map WHERE tenant_id = ?')->execute([$delete_id]);
  $conn_rbe->prepare('DELETE FROM rbe_roles WHERE user_id = ?')->execute([$delete_id]);
  $conn_rbe->prepare('DELETE FROM rbe_users WHERE id = ?')->execute([$delete_id]);
  $message = 'Tenant deleted.';
}

// Versioned save of tenant core fees
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_core_fees'])) {
  $t_id    = (int)($_POST['tenant_id'] ?? 0);
  $sewage  = (float)($_POST['sewage_fee'] ?? 0);
  $refuse  = (float)($_POST['refuse_removal_fee'] ?? 0);
  $rates   = (float)($_POST['rates_and_taxes'] ?? 0);
  $eff_from = trim((string)($_POST['effective_from'] ?? ''));
  if ($eff_from === '' || @DateTime::createFromFormat('Y-m-d', $eff_from) === false) $eff_from = next_cycle_first_day();
  $use_versioning = ($has_effective_from && $has_effective_to && $has_history_table);
  if ($t_id > 0) {
    // Ensure this tenant actually belongs to the scoped landlord
    $ownChk = $conn_rbe->prepare('SELECT landlord_id FROM tenant_landlord_map WHERE tenant_id = ? LIMIT 1');
    $ownChk->execute([$t_id]);
    $owner = (int)$ownChk->fetchColumn();
    if (!$owner || $owner !== (int)$landlord_id) {
      $message = 'Invalid tenant/landlord combination for fee update.';
    } else {
      if ($use_versioning) {
        $conn_rbe->beginTransaction();
        try {
          $prevStmt = $conn_rbe->prepare('SELECT * FROM billing_settings WHERE landlord_id = ? AND tenant_id = ? ORDER BY effective_from DESC LIMIT 1 FOR UPDATE');
          $prevStmt->execute([$landlord_id, $t_id]);
          $prev = $prevStmt->fetch(PDO::FETCH_ASSOC);
          if ($prev) {
            $cols = array_keys($prev);
            $cols_list = '`' . implode('`,`', $cols) . '`';
            $ph = rtrim(str_repeat('?,', count($cols)), ',');
            $insH = $conn_rbe->prepare("INSERT INTO billing_settings_history ({$cols_list}) VALUES ({$ph})");
            $insH->execute(array_values($prev));
            $to_date = (new DateTime($eff_from))->modify('-1 day')->format('Y-m-d');
            $conn_rbe->prepare('UPDATE billing_settings SET effective_to = ? WHERE id = ?')->execute([$to_date, (int)$prev['id']]);
          }
          $conn_rbe->prepare('INSERT INTO billing_settings (landlord_id, tenant_id, sewage_fee, refuse_removal_fee, rates_and_taxes, effective_from, effective_to) VALUES (?, ?, ?, ?, ?, ?, NULL)')->execute([$landlord_id, $t_id, $sewage, $refuse, $rates, $eff_from]);
          $conn_rbe->commit();
          header('Location: manage-tenants.php?landlord_id='.$landlord_id.'&updated=1'); exit;
        } catch (Throwable $e) {
          $conn_rbe->rollBack();
        }
      }
      // Fallback: no versioning
      $exists = $conn_rbe->prepare('SELECT id FROM billing_settings WHERE landlord_id = ? AND tenant_id = ? LIMIT 1');
      $exists->execute([$landlord_id, $t_id]);
      if ($exists->fetchColumn()) {
        $conn_rbe->prepare('UPDATE billing_settings SET sewage_fee=?, refuse_removal_fee=?, rates_and_taxes=? WHERE landlord_id=? AND tenant_id=?')->execute([$sewage,$refuse,$rates,$landlord_id,$t_id]);
      } else {
        $conn_rbe->prepare('INSERT INTO billing_settings (landlord_id, tenant_id, sewage_fee, refuse_removal_fee, rates_and_taxes) VALUES (?, ?, ?, ?, ?)')->execute([$landlord_id,$t_id,$sewage,$refuse,$rates]);
      }
      header('Location: manage-tenants.php?landlord_id='.$landlord_id.'&updated=1'); exit;
    }
  }
}

// Load tenants for table
if ($is_admin && !$landlord_id) {
  $tenants = $conn_rbe->query("SELECT r.user_id AS id, u.fullname, u.email, u.phone, m.landlord_id, m.use_wallet, lu.fullname AS landlord_name FROM rbe_roles r JOIN rbe_users u ON r.user_id=u.id LEFT JOIN tenant_landlord_map m ON m.tenant_id=r.user_id LEFT JOIN rbe_users lu ON lu.id=m.landlord_id WHERE r.role='tenant' ORDER BY u.fullname")->fetchAll(PDO::FETCH_ASSOC);
} else {
  $st = $conn_rbe->prepare('SELECT r.user_id AS id, u.fullname, u.email, u.phone, m.use_wallet FROM rbe_roles r JOIN rbe_users u ON r.user_id=u.id JOIN tenant_landlord_map m ON m.tenant_id=r.user_id WHERE r.role=\'tenant\' AND m.landlord_id=? ORDER BY u.fullname');
  $st->execute([$landlord_id]);
  $tenants = $st->fetchAll(PDO::FETCH_ASSOC);
}

// Extra fees by tenant for prefill
$extra_fees = [];
if ($has_extra_fees) {
  $tenant_ids = array_map('intval', array_column($tenants,'id'));
  if ($tenant_ids) {
    $in = implode(',', array_fill(0, count($tenant_ids), '?'));
    $st = $conn_rbe->prepare("SELECT tenant_id, fee_type, amount, active FROM extra_fees WHERE tenant_id IN ($in)");
    $st->execute($tenant_ids);
    foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
      $extra_fees[(int)$row['tenant_id']][strtolower(trim((string)$row['fee_type']))] = ['amount'=>(float)$row['amount'],'active'=>(int)$row['active']];
    }
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Manage Tenants — RBE</title>
  <link rel="stylesheet" href="/assets/css/theme.css">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
  <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; }
    .card { background:#112537; padding:24px 28px; border-radius:14px; box-shadow:0 4px 14px rgba(0,0,0,0.35); margin:20px auto; max-width:1200px; }
    .nav-btn, .btn { display:inline-block; background:linear-gradient(90deg,#7ed957 0%,#9eff6d 100%); color:#0a1b25; font-weight:600; padding:10px 20px; border-radius:30px; text-decoration:none; border:none; cursor:pointer; }
    .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); }
    table { width:100%; border-collapse:collapse; background:#0b1f33; color:#fff; margin-top:12px; }
    th, td { padding:10px; border-bottom:1px solid rgba(255,255,255,0.08); text-align:left; }
    th { background:#1b3a4d; color:#7ed957; }
    .search-row { display:flex; gap:10px; align-items:center; justify-content:space-between; }
    .banner { background:#0e3620; color:#c2ffd2; border-left:4px solid #7ed957; padding:10px 15px; border-radius:8px; margin:12px 0; font-weight:500; }
    .row { display:flex; gap:10px; }
    .row > div { flex:1; }
    .drawer { position:fixed; top:0; right:-540px; width:540px; height:100%; background:#081621; box-shadow:-4px 0 18px rgba(0,0,0,0.55); transition:right 0.25s ease; padding:22px 22px 28px; overflow:auto; z-index:10000; border-left:1px solid rgba(0,0,0,0.6); }
    .drawer.open { right:0; }
    .drawer h2 { margin-top:4px; margin-bottom:14px; font-size:20px; color:#7ed957; }
    .drawer .card { margin:12px 0; max-width:none; padding:18px 20px; border-radius:12px; box-shadow:0 2px 10px rgba(0,0,0,0.4); }
    .drawer .card h3 { margin-top:0; margin-bottom:10px; font-size:16px; color:#9fe986; }
    .drawer .row { gap:12px; }
    .drawer label { font-size:13px; color:#a8c2de; margin-bottom:4px; display:block; }
    .drawer .inp { font-size:14px; padding:8px 10px; }
    .close-x { position:absolute; top:10px; right:14px; cursor:pointer; color:#7ed957; font-size:22px; line-height:1; padding:4px 6px; border-radius:999px; background:rgba(0,0,0,0.25); }
    .close-x:hover { background:rgba(0,0,0,0.45); transform:scale(1.05); }
    .toggle-row { display:flex; align-items:center; gap:10px; margin:10px 0; padding:8px 10px; border-radius:8px; border:1px solid transparent; transition:0.2s; }
    .toggle-row input[type=checkbox] { width:18px; height:18px; accent-color:#7ed957; }
    .toggle-row.active { background:rgba(126,217,87,0.08); border-color:rgba(126,217,87,0.35); box-shadow:0 0 12px rgba(126,217,87,0.28); }
    .tag { display:inline-block; padding:2px 10px; border-radius:999px; border:1px solid #7ed957; color:#7ed957; font-size:12px; background:#0b1f33; }
  </style>
</head>
<body>

<div class="card" style="display:flex; align-items:center; gap:12px; justify-content:center;">
  <h1 style="margin:0;">Manage Tenants</h1>
  
</div>

<?php if (isset($message)): ?><div class="card banner"><?= esc($message) ?></div><?php endif; ?>

<div class="card">
  <h2>Add New Tenant</h2>
  <form method="post">
    <div class="row">
      <div><input class="inp" type="text" name="fullname" placeholder="Full Name" required></div>
      <div><input class="inp" type="email" name="email" placeholder="Email" required></div>
      <div><input class="inp" type="text" name="phone" placeholder="Phone"></div>
      <?php if ($is_admin): ?>
        <div>
          <select class="inp" name="landlord_id" required>
            <option value="">Assign to Landlord</option>
            <?php $landlords = $conn_rbe->query('SELECT r.user_id, u.fullname FROM rbe_roles r JOIN rbe_users u ON r.user_id=u.id WHERE r.role=\'landlord\' ORDER BY u.fullname');
            foreach ($landlords as $l): ?>
              <option value="<?= (int)$l['user_id'] ?>"><?= esc($l['fullname']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      <?php endif; ?>
    </div>
    <div style="text-align:right; margin-top:8px;"><button class="btn" type="submit" name="add_tenant">Add Tenant</button></div>
  </form>
</div>

<div class="card">
  <div class="search-row">
    <h2 style="margin:0;">Tenants</h2>
    <input id="tenantSearch" class="inp" placeholder="Search tenants by name/email/phone">
  </div>
  <?php if ($is_admin && !$landlord_id): ?><p class="tag" style="margin-top:8px;">Admin mode: select a landlord via ?landlord_id=ID to enable per-tenant management.</p><?php endif; ?>
  <div style="overflow-x:auto;">
    <table id="tenantTable">
      <thead><tr>
        <th>ID</th><th>Name</th><th>Email</th><th>Phone</th>
        <?php if ($is_admin && !$landlord_id): ?><th>Landlord</th><?php endif; ?>
        <th style="text-align:right;">Actions</th>
      </tr></thead>
      <tbody>
        <?php foreach ($tenants as $t): ?>
          <tr data-tenant='<?= esc(json_encode($t)) ?>'>
            <td><?= (int)$t['id'] ?></td>
            <td><?= esc($t['fullname']) ?></td>
            <td><?= esc($t['email']) ?></td>
            <td><?= esc($t['phone']) ?></td>
            <?php if ($is_admin && !$landlord_id): ?><td><?= esc($t['landlord_name'] ?? 'Unassigned') ?></td><?php endif; ?>
            <td style="text-align:right; white-space:nowrap;">
              <?php if ($landlord_id): ?><button class="btn" type="button" onclick="openDrawer(<?= (int)$t['id'] ?>)">Manage</button><?php endif; ?>
              <a class="btn" style="background:#ff6d6d; color:#0b1f2c;" href="?delete=<?= (int)$t['id'] ?>" onclick="return confirm('Delete this tenant?')">Delete</a>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Drawer -->
<div id="tenantDrawer" class="drawer" aria-hidden="true">
  <div class="close-x" onclick="closeDrawer()">✕</div>
  <h2 id="drawerTitle">Tenant</h2>
  <div class="card" style="margin:0;">
    <h3>Profile</h3>
    <div class="row">
      <div><label>Name</label><input class="inp" id="d_name" readonly></div>
      <div><label>Email</label><input class="inp" id="d_email" readonly></div>
    </div>
    <div class="row" style="margin-top:8px;"><div><label>Phone</label><input class="inp" id="d_phone" readonly></div></div>
  </div>

  <div class="card" style="margin:16px 0 0 0;">
    <h3>Energy Snapshot (This Month)</h3>
    <p class="tag">Grid vs Generator vs Solar based on Flecto + IAM readings.</p>
    <?php
      $snapshot = ['grid_kwh'=>0.0,'gen_kwh'=>0.0,'solar_kwh'=>0.0,'total_kwh'=>0.0];
      if ($landlord_id && !empty($tenants)) {
        // Filled dynamically in JS when a tenant is opened via drawer using a lightweight API, or left as static text for now.
      }
    ?>
    <p style="color:#c8d6e5; font-size:14px; margin-top:6px;">
      Values for the selected tenant are shown on the Tenant Dashboard and landlord dashboard Billing Snapshot.
    </p>
  </div>

  <div class="card" style="margin:16px 0 0 0;">
    <h3>Core Fees (Versioned)</h3>
    <?php if (!($has_effective_from && $has_effective_to && $has_history_table)): ?><p class="tag">Versioning not available (schema missing).</p><?php endif; ?>
    <form method="post">
      <input type="hidden" name="save_core_fees" value="1">
      <input type="hidden" name="tenant_id" id="d_tenant_id">
      <div class="row">
        <div><label>Sewage Fee (R)</label><input class="inp" type="number" step="0.01" name="sewage_fee" id="d_sewage"></div>
        <div><label>Refuse Fee (R)</label><input class="inp" type="number" step="0.01" name="refuse_removal_fee" id="d_refuse"></div>
        <div><label>Rates &amp; Taxes (R)</label><input class="inp" type="number" step="0.01" name="rates_and_taxes" id="d_rates"></div>
      </div>
      <div class="row" style="margin-top:8px;">
        <div><label>Effective From</label><input class="inp" type="date" name="effective_from" id="d_eff_from" value="<?= esc(next_cycle_first_day()) ?>"></div>
        <div><label>Effective To (last)</label><input class="inp" id="d_eff_to" readonly></div>
        <div style="display:flex; align-items:flex-end; justify-content:flex-end;"><button class="btn" type="submit">Save</button></div>
      </div>
    </form>
  </div>

  <div class="card" style="margin:16px 0 0 0;">
    <h3>Extra Utility Fees</h3>
    <?php if (!$has_extra_fees): ?><p class="tag">extra_fees table missing. UI disabled.</p><?php endif; ?>
    <?php $feeTypes=[
      'aircon_fee'=>'Aircon Fee',
      'generator_fee'=>'Generator Fee',
      'elec_avail_fee'=>'Electricity Availability Fee',
      'elec_basic_fee'=>'Electricity Basic Fee',
      'water_avail_fee'=>'Water Availability Fee',
      'water_basic_fee'=>'Water Basic Fee',
    ]; ?>
    <?php foreach ($feeTypes as $k=>$lbl): ?>
      <div class="toggle-row" data-key="<?= esc($k) ?>">
        <input type="checkbox" id="cb_<?= esc($k) ?>" <?= $has_extra_fees?'':'disabled' ?> >
        <label for="cb_<?= esc($k) ?>" style="min-width:230px;">&nbsp;<?= esc($lbl) ?></label>
        <input type="number" step="0.01" class="inp" style="max-width:160px;" id="amt_<?= esc($k) ?>" placeholder="0.00" <?= $has_extra_fees?'':'disabled' ?> >
        <button class="btn" type="button" onclick="saveExtraFee('<?= esc($k) ?>')" <?= $has_extra_fees?'':'disabled' ?> >Update</button>
      </div>
    <?php endforeach; ?>
  </div>

  <div class="card" style="margin:16px 0 0 0;">
    <h3>Wallet</h3>
    <form method="post" action="wallet/wallet_toggle.php">
      <input type="hidden" name="landlord_id" value="<?= $landlord_id ?>">
      <input type="hidden" name="single_mode" value="1">
      <input type="hidden" name="tenant_id" id="wallet_tenant_id" value="0">
      <label><input type="checkbox" id="d_wallet_cb" name="wallet_enabled" value="1"> Enable wallet for this tenant</label>
      <div style="margin-top:8px;"><button class="btn" type="submit">Save</button></div>
    </form>
  </div>
</div>

<script>
  const hasExtraFees = <?= $has_extra_fees ? 'true' : 'false' ?>;
  const extraFeesData = <?= json_encode($extra_fees) ?>;
  const landlordId = <?= (int)$landlord_id ?>;
  const tenants = Array.from(document.querySelectorAll('#tenantTable tbody tr')).map(tr => JSON.parse(tr.dataset.tenant));

  function initExtraFeeToggles() {
    ['aircon_fee','generator_fee','elec_avail_fee','elec_basic_fee','water_avail_fee','water_basic_fee'].forEach(k => {
      const cb = document.getElementById('cb_'+k);
      const amt = document.getElementById('amt_'+k);
      if (!cb || !amt) return;
      const row = cb.closest('.toggle-row');
      cb.addEventListener('change', () => {
        if (!row) return;
        if (cb.checked) {
          row.classList.add('active');
          amt.disabled = false;
        } else {
          row.classList.remove('active');
          amt.disabled = true;
        }
      });
    });
  }

  function openDrawer(tenantId) {
    const t = tenants.find(x => parseInt(x.id) === parseInt(tenantId));
    if (!t) return;
    document.getElementById('drawerTitle').innerText = `Tenant #${t.id}`;
    document.getElementById('d_name').value = t.fullname || '';
    document.getElementById('d_email').value = t.email || '';
    document.getElementById('d_phone').value = t.phone || '';
    document.getElementById('d_tenant_id').value = t.id;
    const walletTid = document.getElementById('wallet_tenant_id');
    if (walletTid) walletTid.value = t.id;
    // Wallet: set checked state to match current mapping
    const walletCb = document.getElementById('d_wallet_cb');
    if (walletCb) {
      walletCb.checked = parseInt(t.use_wallet || 0, 10) === 1;
    }
    // Prefill extra fees
    if (hasExtraFees) {
      const byType = extraFeesData && extraFeesData.hasOwnProperty(t.id) ? extraFeesData[t.id] : {};
      ['aircon_fee','generator_fee','elec_avail_fee','elec_basic_fee','water_avail_fee','water_basic_fee'].forEach(k => {
        const cb = document.getElementById('cb_'+k);
        const amt = document.getElementById('amt_'+k);
        const rec = byType && byType[k] ? byType[k] : { amount: 0, active: 0 };
        if (cb) cb.checked = (parseInt(rec.active, 10) === 1);
        if (amt) {
          amt.value = rec.amount || '';
          amt.disabled = !(cb && cb.checked);
        }
        const row = cb ? cb.closest('.toggle-row') : null;
        if (row) {
          if (cb && cb.checked) row.classList.add('active'); else row.classList.remove('active');
        }
      });
    }
    const d = document.getElementById('tenantDrawer'); d.classList.add('open'); d.setAttribute('aria-hidden','false');
  }
  function closeDrawer(){ const d=document.getElementById('tenantDrawer'); d.classList.remove('open'); d.setAttribute('aria-hidden','true'); }

  function saveExtraFee(key) {
    if (!hasExtraFees) return alert('extra_fees table missing');
    const tid = parseInt(document.getElementById('d_tenant_id').value, 10);
    const cb = document.getElementById('cb_'+key);
    const amt = document.getElementById('amt_'+key);
    const active = cb && cb.checked ? 1 : 0;
    const amount = (!active) ? 0 : parseFloat(amt.value || '0');
    fetch('/api/billing/extra_fee_toggle.php', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ tenant_id: tid, fee_type: key, active: active, amount: amount }) })
      .then(r => r.json()).then(data => {
        if (!data || data.status !== 'ok') throw new Error('Update failed');
        if (!extraFeesData.hasOwnProperty(tid)) extraFeesData[tid] = {};
        extraFeesData[tid][key] = { amount: amount, active: active };
        alert('Fee updated');
      }).catch(() => alert('Failed to update extra fee'));
  }

  // Client search
  const s = document.getElementById('tenantSearch');
  const table = document.getElementById('tenantTable');
  s?.addEventListener('input', () => {
    const q = s.value.toLowerCase();
    table.querySelectorAll('tbody tr').forEach(tr => {
      const cells = Array.from(tr.cells).slice(1, 4).map(td => (td.innerText||'').toLowerCase());
      tr.style.display = cells.some(v => v.includes(q)) ? '' : 'none';
    });
  });

  // Initialise fee toggle behaviour once
  initExtraFeeToggles();
</script>

</body>
</html>
