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

require_login();

// Admin only
if ($_SESSION['user']['role'] !== 'admin') {
  http_response_code(403);
  exit('Forbidden');
}

$user = current_user();

$unitId = (int)($_GET['unit_id'] ?? 0);
if (!$unitId) exit('Invalid unit.');

// Load unit header info
$stmt = db()->prepare("
  SELECT u.unit_code, b.name AS building_name
  FROM units u
  JOIN buildings b ON b.id = u.building_id
  WHERE u.id = ?
  LIMIT 1
");
$stmt->execute([$unitId]);
$unitInfo = $stmt->fetch();
if (!$unitInfo) exit('Unit not found.');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';

  try {
    if ($action === 'add') {
      $name = trim($_POST['full_name'] ?? '');
      $phone = trim($_POST['phone'] ?? '');
      $email = trim($_POST['email'] ?? '');

      if ($name === '') {
        $error = 'Tenant name is required.';
      } else {
        Tenant::create($unitId, $name, $phone, $email);

        // ✅ notify admins
        Notification::notifyAdmins(
          'tenant_added',
          'Tenant added',
          ($user['full_name'] ?? 'Admin') . " added tenant {$name} to Unit " . ($unitInfo['unit_code'] ?? '') . ".",
          "/unit.php?id=" . (int)$unitId,
          (int)($user['id'] ?? null)
        );

        $success = 'Tenant added successfully ✅';
      }
    }

    if ($action === 'toggle') {
      $tenantId = (int)($_POST['tenant_id'] ?? 0);
      $active = (int)($_POST['active'] ?? 0);

      if ($tenantId) {
        Tenant::setActive($tenantId, $active);
        $success = 'Tenant status updated ✅';
      }
    }

  } catch (Throwable $e) {
    $error = $e->getMessage();
  }
}

$tenants = Tenant::listByUnit($unitId);

$pageTitle = 'Manage Tenants - ' . ($unitInfo['unit_code'] ?? '');
require_once __DIR__ . '/../app/views/partials/header.php';
?>

<div class="container">

  <div class="mb-3">
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/unit.php?id=<?= (int)$unitId ?>">← Back to Unit</a>
  </div>

  <div class="card p-4 mb-3">
    <h5 class="page-title mb-1">Manage Tenants</h5>
    <div class="text-muted">
      <?= htmlspecialchars($unitInfo['building_name'] ?? '') ?> • Unit <?= htmlspecialchars($unitInfo['unit_code'] ?? '') ?>
    </div>

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

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

    <hr>

    <form method="post" class="row g-2">
      <input type="hidden" name="action" value="add">

      <div class="col-md-4">
        <label class="form-label">Full name</label>
        <input name="full_name" class="form-control" required>
      </div>

      <div class="col-md-4">
        <label class="form-label">Phone</label>
        <input name="phone" class="form-control">
      </div>

      <div class="col-md-4">
        <label class="form-label">Email</label>
        <input name="email" type="email" class="form-control">
      </div>

      <div class="col-12">
        <button class="btn btn-primary w-100 mt-2">Add Tenant</button>
      </div>
    </form>
  </div>

  <div class="card p-4">
    <h6 class="mb-3">Tenants</h6>

    <?php if (!$tenants): ?>
      <div class="text-muted">No tenants yet.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table table-sm align-middle">
          <thead>
            <tr>
              <th>Name</th>
              <th>Phone</th>
              <th>Email</th>
              <th>Status</th>
              <th class="text-end">Action</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($tenants as $t): ?>
              <tr>
                <td><?= htmlspecialchars($t['full_name'] ?? '') ?></td>
                <td><?= htmlspecialchars($t['phone'] ?? '') ?></td>
                <td><?= htmlspecialchars($t['email'] ?? '') ?></td>
                <td>
                  <?php if ((int)($t['is_active'] ?? 0) === 1): ?>
                    <span class="badge bg-success">Active</span>
                  <?php else: ?>
                    <span class="badge bg-secondary">Offboarded</span>
                  <?php endif; ?>
                </td>
                <td class="text-end">
                  <form method="post" class="d-inline">
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="tenant_id" value="<?= (int)$t['id'] ?>">
                    <input type="hidden" name="active" value="<?= ((int)$t['is_active'] === 1) ? 0 : 1 ?>">
                    <button class="btn btn-sm btn-outline-primary">
                      <?= ((int)$t['is_active'] === 1) ? 'Offboard' : 'Activate' ?>
                    </button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>

  </div>

</div>

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