<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/middleware/auth.php';
require_once __DIR__ . '/../app/config/db.php';

require_login();
$user = current_user();
if (($user['role'] ?? '') !== 'admin') { http_response_code(403); exit('Forbidden'); }

$id = (int)($_GET['id'] ?? 0);
if (!$id) exit('Invalid tenant.');

// Load tenant
$stmt = db()->prepare("
  SELECT t.*, u.unit_code, b.name AS building_name
  FROM tenants t
  JOIN units u ON u.id = t.unit_id
  JOIN buildings b ON b.id = u.building_id
  WHERE t.id = ?
  LIMIT 1
");
$stmt->execute([$id]);
$tenant = $stmt->fetch();
if (!$tenant) exit('Tenant not found.');

// Units dropdown (for transfer)
$unitsStmt = db()->query("
  SELECT u.id, u.unit_code, b.name AS building_name
  FROM units u
  JOIN buildings b ON b.id = u.building_id
  ORDER BY b.name ASC, u.unit_code ASC
");
$units = $unitsStmt->fetchAll();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $name = trim($_POST['full_name'] ?? '');
  $phone = trim($_POST['phone'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $newUnitId = (int)($_POST['unit_id'] ?? 0);

  if ($name === '') {
    $error = 'Full name is required.';
  } elseif ($newUnitId <= 0) {
    $error = 'Please select a unit.';
  } else {
    db()->prepare("UPDATE tenants SET full_name=?, phone=?, email=?, unit_id=? WHERE id=?")
      ->execute([$name, $phone, $email, $newUnitId, $id]);

    $success = 'Tenant updated (and transferred if unit changed) ✅';

    // reload updated tenant info
    $stmt->execute([$id]);
    $tenant = $stmt->fetch();
  }
}

$pageTitle = 'Edit Tenant';
require_once __DIR__ . '/../app/views/partials/header.php';
?>

<div class="container-narrow mx-auto">

  <!-- ✅ Standard back buttons -->
  <div class="mb-3 d-flex gap-2 flex-wrap">
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/tenants_list.php">← Back to Tenants</a>
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/units_list.php">Units List</a>
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/dashboard.php">Dashboard</a>
  </div>

  <div class="card p-4">
    <h5 class="page-title mb-1">Edit Tenant</h5>
    <div class="text-muted mb-3">
      Current: <?= htmlspecialchars($tenant['building_name']) ?> • Unit <?= htmlspecialchars($tenant['unit_code']) ?>
    </div>

    <?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>
    <?php if ($success): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>

    <form method="post">

      <div class="mb-3">
        <label class="form-label">Tenant Name</label>
        <input name="full_name" class="form-control" required value="<?= htmlspecialchars($tenant['full_name']) ?>">
      </div>

      <div class="row g-2">
        <div class="col-md-6">
          <div class="mb-3">
            <label class="form-label">Phone</label>
            <input name="phone" class="form-control" value="<?= htmlspecialchars($tenant['phone'] ?? '') ?>">
          </div>
        </div>
        <div class="col-md-6">
          <div class="mb-3">
            <label class="form-label">Email</label>
            <input name="email" type="email" class="form-control" value="<?= htmlspecialchars($tenant['email'] ?? '') ?>">
          </div>
        </div>
      </div>

      <!-- ✅ TRANSFER DROPDOWN -->
      <div class="mb-4">
        <label class="form-label">Transfer to Unit</label>
        <select name="unit_id" class="form-select" required>
          <option value="">Select unit</option>
          <?php foreach ($units as $u): ?>
            <option value="<?= (int)$u['id'] ?>" <?= ((int)$tenant['unit_id'] === (int)$u['id']) ? 'selected' : '' ?>>
              <?= htmlspecialchars($u['building_name']) ?> — <?= htmlspecialchars($u['unit_code']) ?>
            </option>
          <?php endforeach; ?>
        </select>
        <div class="form-text">Changing the unit here will move the tenant to that unit.</div>
      </div>

      <button class="btn btn-primary w-100">Save Changes</button>
    </form>
  </div>

</div>

<?php require_once __DIR__ . '/../app/views/partials/footer.php'; ?>
