<?php
require_once __DIR__ . '/../../core/auth.php';
require_login();
$role = current_user_role();

// Include sidebar
if ($role === 'admin') {
  @include __DIR__ . '/../../admin-nav.php';
} else {
  @include __DIR__ . '/../../landlord-nav.php';
}

// Admin landlord select
$landlords = [];
if ($role === 'admin') {
  require_once __DIR__ . '/../../core/db_connect.php';
  $landlords = $conn_rbe->query("SELECT u.id, u.fullname FROM rbe_users u JOIN rbe_roles r ON r.user_id=u.id AND r.role='landlord' ORDER BY u.fullname")->fetchAll(PDO::FETCH_ASSOC);
}
?>
<link rel="stylesheet" href="/assets/css/theme.css">
<link rel="stylesheet" href="../billing/billing.css">
<style>
  /* Offset for fixed sidebar */
  body { 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; } }
  .card { max-width: 1100px; margin: 20px auto; }
  #tenantList .card { padding: 12px; }
  #tenantList label { display: flex; align-items: center; gap: 8px; }
  #landlordSelect { max-width: 360px; }
  #walletForm { max-width: 1100px; }
  button.btn { margin-top: 8px; }
  </style>

<div class="card" style="margin:20px;">
  <h2>Wallet Settings</h2>
  <?php if ($role === 'admin'): ?>
    <label>Landlord</label>
    <select id="landlordSelect">
      <option value="">-- Select --</option>
      <?php foreach ($landlords as $l): ?>
        <option value="<?= (int)$l['id'] ?>"><?= htmlspecialchars($l['fullname']) ?></option>
      <?php endforeach; ?>
    </select>
  <?php endif; ?>

  <form id="walletForm" style="margin-top:12px;">
    <input type="hidden" name="action" value="save_wallet_settings">
    <?php if ($role === 'admin'): ?><input type="hidden" name="landlord_id" id="landlord_id"><?php endif; ?>
    <div style="margin:8px 0;">
      <label><input type="checkbox" id="use_wallet"> Enable Wallet for Landlord</label>
    </div>
    <div id="tenantList" class="grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:8px;"></div>
    <button type="submit" class="btn" style="margin-top:12px;">Save</button>
  </form>
</div>

<script>
const api = 'wallet-back.php';
let landlord_id = null;

async function loadWallet() {
  const q = new URLSearchParams({ action: 'get_wallet_settings' });
  if (landlord_id) q.set('landlord_id', landlord_id);
  const res = await fetch(`${api}?${q.toString()}`);
  const j = await res.json();
  if (j.status !== 'success') return;
  const { landlord_use_wallet, tenants } = j.data;
  document.getElementById('use_wallet').checked = !!landlord_use_wallet;
  const wrap = document.getElementById('tenantList');
  wrap.innerHTML = '';
  tenants.forEach(t => {
    const id = t.tenant_id;
    const name = t.fullname;
    const chk = !!Number(t.use_wallet);
    const item = document.createElement('div');
    item.className = 'card';
    item.innerHTML = `<label><input type="checkbox" name="tenants[${id}]" ${chk?'checked':''}> ${name}</label>`;
    wrap.appendChild(item);
  });
}

document.addEventListener('DOMContentLoaded', () => {
  const f = document.getElementById('walletForm');
  f.addEventListener('submit', async (e) => {
    e.preventDefault();
    const fd = new FormData(f);
    if (landlord_id) fd.set('landlord_id', landlord_id);
    fd.set('use_wallet', document.getElementById('use_wallet').checked ? '1' : '0');
    const res = await fetch(api, { method: 'POST', body: fd });
    const j = await res.json();
    alert(j.message || 'Saved');
    loadWallet();
  });

  const sel = document.getElementById('landlordSelect');
  if (sel) {
    sel.addEventListener('change', () => {
      landlord_id = sel.value || null;
      const hidden = document.getElementById('landlord_id');
      if (hidden) hidden.value = landlord_id || '';
      if (landlord_id) loadWallet();
    });
  }

  loadWallet();
});
</script>
