<?php
// ============================================================
// manage-landlords.php — RBE Utilities
// ------------------------------------------------------------
// Admin-only landlord management interface
// Drawer-based UI (matches manage-tenants.php design)
// Includes:
// - Add/Edit/Delete landlords
// - Wallet enable/disable toggle
// - View Dashboard link
// - AJAX endpoints (?action=...)
// ============================================================

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once __DIR__ . '/core/db_connect.php';


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

$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
if ($stmt->fetchColumn() !== 'admin') {
    exit('Access denied.');
}

// ------------------------------------------------------------
// API HANDLER (AJAX)
// ------------------------------------------------------------
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    $action = $_GET['action'];

    try {
        switch ($action) {

            case 'get_landlords':
                $stmt = $conn_rbe->query("SELECT u.id, u.fullname, u.email, u.phone, u.use_wallet, COUNT(p.id) AS property_count
                    FROM rbe_users u
                    JOIN rbe_roles r ON r.user_id = u.id
                    LEFT JOIN properties p ON p.landlord_id = u.id
                    WHERE r.role = 'landlord'
                    GROUP BY u.id
                    ORDER BY u.fullname ASC");
                echo json_encode(['status' => 'success', 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
                break;

            case 'add_landlord':
                $fullname = trim($_POST['fullname'] ?? '');
                $email = trim($_POST['email'] ?? '');
                $phone = trim($_POST['phone'] ?? '');
                $use_wallet = !empty($_POST['use_wallet']) ? 1 : 0;

                if (!$fullname || !$email) {
                    throw new Exception("Full name and email are required.");
                }

                // Step 1: Find or create standalone RBE user
                $stmt = $conn_rbe->prepare("SELECT id FROM rbe_users WHERE email=? LIMIT 1");
                $stmt->execute([$email]);
                $new_id = (int)($stmt->fetchColumn() ?: 0);
                if ($new_id > 0) {
                    $stmt = $conn_rbe->prepare("UPDATE rbe_users SET fullname=?, phone=?, use_wallet=?, is_active=1, is_deleted=0 WHERE id=?");
                    $stmt->execute([$fullname, $phone, $use_wallet, $new_id]);
                } else {
                    $stmt = $conn_rbe->prepare("INSERT INTO rbe_users (fullname, email, phone, use_wallet, must_set_password, is_active, is_deleted) VALUES (?, ?, ?, ?, 1, 1, 0)");
                    $stmt->execute([$fullname, $email, $phone, $use_wallet]);
                    $new_id = (int)$conn_rbe->lastInsertId();
                }

                // Step 2: Assign role
                $conn_rbe->prepare("INSERT IGNORE INTO rbe_roles (user_id, role) VALUES (?, 'landlord')")->execute([$new_id]);

                echo json_encode(['status' => 'success', 'message' => "Landlord added successfully."]);
                break;

            case 'edit_landlord':
                $id = (int)$_POST['id'];
                $fullname = trim($_POST['fullname'] ?? '');
                $email = trim($_POST['email'] ?? '');
                $phone = trim($_POST['phone'] ?? '');
                $use_wallet = !empty($_POST['use_wallet']) ? 1 : 0;

                $stmt = $conn_rbe->prepare("UPDATE rbe_users SET fullname=?, email=?, phone=?, use_wallet=? WHERE id=?");
                $stmt->execute([$fullname, $email, $phone, $use_wallet, $id]);
                echo json_encode(['status' => 'success', 'message' => "Landlord updated successfully."]);
                break;

            case 'delete_landlord':
                $id = (int)$_POST['id'];

                $conn_rbe->prepare("DELETE FROM login_tokens WHERE user_id=?")->execute([$id]);
                $conn_rbe->prepare("DELETE FROM rbe_roles WHERE user_id=?")->execute([$id]);
                $conn_rbe->prepare("DELETE FROM properties WHERE landlord_id=?")->execute([$id]);
                $conn_rbe->prepare("DELETE FROM rbe_users WHERE id=?")->execute([$id]);

                echo json_encode(['status' => 'success', 'message' => "Landlord deleted successfully."]);
                break;

            case 'toggle_wallet':
                $id = (int)$_POST['id'];
                $use_wallet = (int)$_POST['use_wallet'];
                $conn_rbe->prepare("UPDATE rbe_users SET use_wallet=? WHERE id=?")->execute([$use_wallet, $id]);
                echo json_encode(['status' => 'success', 'message' => "Wallet setting updated."]);
                break;

            default:
                echo json_encode(['status' => 'error', 'message' => 'Unknown action.']);
        }
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Landlords — RBE Utilities</title>
<link rel="stylesheet" href="modules/billing/billing.css">
<style>
.table-actions { display:flex; gap:8px; justify-content:flex-end; }
.drawer { display:none; position:fixed; top:0; right:0; width:400px; height:100%; background:var(--card); box-shadow:-2px 0 15px rgba(0,0,0,0.4); padding:25px; overflow-y:auto; z-index:999; }
.drawer.active { display:block; animation:fadeIn 0.3s ease; }
.drawer h2 { color:var(--accent2); margin-top:0; }
.overlay { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.6); z-index:998; }
.overlay.active { display:block; }
.toggle { cursor:pointer; }
</style>
</head>
<body>
<div class="navbar">
  <h1>Manage Landlords</h1>
  <button class="btn secondary" onclick="window.location='admin-dashboard.php'">⬅ Back</button>
</div>

<div class="section active">
  <div class="card">
    <div style="display:flex;justify-content:space-between;align-items:center;">
      <h2>👤 Landlord Directory</h2>
      <button class="btn" onclick="openDrawer()">➕ Add Landlord</button>
    </div>
    <input id="searchInput" placeholder="Search landlords..." style="width:100%;margin:10px 0;">
    <div id="landlordTable"></div>
  </div>
</div>

<div class="overlay" id="overlay" onclick="closeDrawer()"></div>

<div class="drawer" id="drawer">
  <h2 id="drawerTitle">Add Landlord</h2>
  <form id="landlordForm">
    <input type="hidden" name="id" id="landlordId">
    <label>Full Name</label>
    <input type="text" name="fullname" id="fullname" required>
    <label>Email</label>
    <input type="email" name="email" id="email" required>
    <label>Phone</label>
    <input type="text" name="phone" id="phone">
    <label><input type="checkbox" name="use_wallet" id="use_wallet"> Enable Wallet</label>
    <button class="btn" type="submit">Save</button>
  </form>
</div>

<script>
const api = 'manage-landlords.php';
document.addEventListener("DOMContentLoaded", loadLandlords);

async function loadLandlords() {
  const res = await fetch(api + '?action=get_landlords');
  const data = await res.json();
  const cont = document.getElementById('landlordTable');
  cont.innerHTML = "";
  if (data.status !== 'success' || !data.data.length) {
    cont.innerHTML = "<p style='color:var(--muted)'>No landlords found.</p>";
    return;
  }

  const tbl = document.createElement('table');
  tbl.innerHTML = `
    <tr>
      <th>ID</th><th>Full Name</th><th>Email</th><th>Phone</th>
      <th>Wallet</th><th>Properties</th><th>Actions</th>
    </tr>`;
  data.data.forEach(l => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${l.id}</td>
      <td>${l.fullname}</td>
      <td>${l.email}</td>
      <td>${l.phone || ''}</td>
      <td>
        <input type="checkbox" ${l.use_wallet==1?'checked':''}
          onchange="toggleWallet(${l.id}, this.checked)">
      </td>
      <td>${l.property_count}</td>
      <td class='table-actions'>
        <button class="btn secondary" onclick="viewDashboard(${l.id})">📊</button>
        <button class="btn secondary" onclick="editLandlord(${l.id}, '${l.fullname}', '${l.email}', '${l.phone||''}', ${l.use_wallet})">✏️</button>
        <button class="delete-btn" onclick="deleteLandlord(${l.id})">🗑️</button>
      </td>`;
    tbl.appendChild(tr);
  });
  cont.appendChild(tbl);
}

async function saveLandlord(e) {
  e.preventDefault();
  const form = new FormData(e.target);
  const id = form.get('id');
  const action = id ? 'edit_landlord' : 'add_landlord';
  const res = await fetch(api + '?action=' + action, {method:'POST', body:form});
  const j = await res.json();
  alert(j.message);
  closeDrawer();
  loadLandlords();
}

async function deleteLandlord(id) {
  if (!confirm("Delete this landlord?")) return;
  const res = await fetch(api + '?action=delete_landlord', {method:'POST', body:new URLSearchParams({id})});
  const j = await res.json();
  alert(j.message);
  loadLandlords();
}

async function toggleWallet(id, checked) {
  const use_wallet = checked ? 1 : 0;
  await fetch(api + '?action=toggle_wallet', {method:'POST', body:new URLSearchParams({id, use_wallet})});
}

function viewDashboard(id) {
  window.open(`landlord-dashboard.php?landlord_id=${id}`, '_blank');
}

function openDrawer() {
  document.getElementById('overlay').classList.add('active');
  document.getElementById('drawer').classList.add('active');
  document.getElementById('landlordForm').reset();
  document.getElementById('drawerTitle').textContent = "Add Landlord";
  document.getElementById('landlordId').value = '';
}
function closeDrawer() {
  document.getElementById('overlay').classList.remove('active');
  document.getElementById('drawer').classList.remove('active');
}
function editLandlord(id, fullname, email, phone, use_wallet) {
  openDrawer();
  document.getElementById('drawerTitle').textContent = "Edit Landlord";
  document.getElementById('landlordId').value = id;
  document.getElementById('fullname').value = fullname;
  document.getElementById('email').value = email;
  document.getElementById('phone').value = phone;
  document.getElementById('use_wallet').checked = use_wallet == 1;
}
document.getElementById('landlordForm').addEventListener('submit', saveLandlord);
</script>
</body>
</html>
