<?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_login();
$user = current_user();
if (($user['role'] ?? '') !== 'admin') { http_response_code(403); exit('Forbidden'); }

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

// Units dropdown data (for Add Tenant)
$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();

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

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

      if ($unitId <= 0) {
        $error = "Please select a unit.";
      } elseif ($name === '') {
        $error = "Tenant name is required.";
      } else {
        // Use your model method (either createWithUnit or create)
        if (method_exists('Tenant', 'createWithUnit')) {
          Tenant::createWithUnit($unitId, $name, $phone, $email);
        } else {
          Tenant::create($unitId, $name, $phone, $email);
        }
        $success = "Tenant added successfully ✅";
      }
    }

    if ($action === 'toggle') {
      $id = (int)($_POST['id'] ?? 0);
      $active = (int)($_POST['active'] ?? 0);
      if ($id) {
        db()->prepare("UPDATE tenants SET is_active=? WHERE id=?")->execute([$active, $id]);
        $success = "Tenant status updated ✅";
      }
    }

    if ($action === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      if ($id) {
        db()->prepare("DELETE FROM tenants WHERE id=?")->execute([$id]);
        $success = "Tenant deleted ✅";
      }
    }
  } catch (Throwable $e) {
    $error = $e->getMessage();
  }
}

// Search
$q = trim($_GET['q'] ?? '');

$sql = "
  SELECT
    t.id, t.full_name, t.phone, t.email, t.is_active, t.created_at,
    u.id AS unit_id, 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
";

$params = [];

if ($q !== '') {
  $sql .= " WHERE (t.full_name LIKE ? OR t.phone LIKE ? OR t.email LIKE ? OR u.unit_code LIKE ? OR b.name LIKE ?)";
  $params = array_fill(0, 5, "%$q%");
}

$sql .= " ORDER BY t.is_active DESC, t.full_name ASC";

$stmt = db()->prepare($sql);
$stmt->execute($params);
$tenants = $stmt->fetchAll();

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

<div class="container">

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


  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
    <div>
      <h5 class="page-title mb-1">Tenants</h5>
      <div class="text-muted">Add, search, update status (active/offboarded), and manage tenants across all units.</div>
    </div>
    <div class="d-flex gap-2 flex-wrap">
      <a href="<?= BASE_URL ?>/units_list.php" class="btn btn-outline-primary">Units List</a>
      <a href="<?= BASE_URL ?>/admin_add_unit.php" class="btn btn-primary">+ Add Unit</a>
    </div>
  </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; ?>

  <!-- ADD TENANT -->
  <div class="card p-4 mb-3">
    <h6 class="mb-3">Add Tenant</h6>
    <?php if (!$units): ?>
      <div class="text-muted">No units available yet. Add a building and unit first.</div>
    <?php else: ?>
      <form method="post">
        <input type="hidden" name="action" value="add">

        <div class="mb-3">
          <label class="form-label">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'] ?>">
                <?= htmlspecialchars($u['building_name']) ?> — <?= htmlspecialchars($u['unit_code']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="mb-3">
          <label class="form-label">Tenant Name</label>
          <input name="full_name" class="form-control" required placeholder="Full name">
        </div>

        <div class="row g-2">
          <div class="col-md-6">
            <div class="mb-3">
              <label class="form-label">Phone (optional)</label>
              <input name="phone" class="form-control" placeholder="09xxxxxxxxx">
            </div>
          </div>
          <div class="col-md-6">
            <div class="mb-3">
              <label class="form-label">Email (optional)</label>
              <input name="email" type="email" class="form-control" placeholder="tenant@email.com">
            </div>
          </div>
        </div>

        <button class="btn btn-primary w-100">Add Tenant</button>
      </form>
    <?php endif; ?>
  </div>

  <!-- SEARCH -->
  <div class="card p-3 mb-3">
    <form method="get" class="row g-2 align-items-center">
      <div class="col-md-10">
        <input name="q" class="form-control" value="<?= htmlspecialchars($q) ?>"
               placeholder="Search tenant name, phone, email, building, unit code...">
      </div>
      <div class="col-md-2 d-grid">
        <button class="btn btn-outline-primary">Search</button>
      </div>
    </form>
  </div>

  <!-- LIST -->
  <div class="card p-3">
    <?php if (!$tenants): ?>
      <div class="text-muted p-3">No tenants found.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle mb-0">
          <thead>
            <tr>
              <th>Name</th>
              <th>Contact</th>
              <th>Unit</th>
              <th>Status</th>
              <th class="text-end">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($tenants as $t): ?>
              <tr>
                <td><?= htmlspecialchars($t['full_name']) ?></td>
                <td class="text-muted small">
                  <?= htmlspecialchars($t['phone'] ?? '') ?>
                  <?= ($t['email'] ? ' • ' . htmlspecialchars($t['email']) : '') ?>
                </td>
                <td>
                  <div class="fw-semibold"><?= htmlspecialchars($t['building_name']) ?></div>
                  <div class="text-muted small">Unit <?= htmlspecialchars($t['unit_code']) ?></div>
                </td>
                <td>
                  <?php if ((int)$t['is_active'] === 1): ?>
                    <span class="badge text-bg-success">Active</span>
                  <?php else: ?>
                    <span class="badge text-bg-secondary">Offboarded</span>
                  <?php endif; ?>
                </td>
                <td class="text-end">
                  <a class="btn btn-sm btn-outline-primary"
                     href="<?= BASE_URL ?>/admin_edit_tenant.php?id=<?= (int)$t['id'] ?>">
                    Edit
                  </a>

                  <a class="btn btn-sm btn-outline-primary"
                     href="<?= BASE_URL ?>/unit.php?id=<?= (int)$t['unit_id'] ?>">
                    View Unit
                  </a>

                  <form method="post" class="d-inline">
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="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-<?= ((int)$t['is_active'] === 1) ? 'danger' : 'primary' ?>">
                      <?= ((int)$t['is_active'] === 1) ? 'Offboard' : 'Activate' ?>
                    </button>
                  </form>

                  <form method="post" class="d-inline" onsubmit="return confirm('Delete this tenant permanently?');">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= (int)$t['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger">Delete</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>

</div>

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