<?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();
$isAdmin = (($user['role'] ?? '') === 'admin');

$pageTitle = 'Units';
require_once __DIR__ . '/../app/views/partials/header.php';

// Filters
$buildingId = (int)($_GET['building_id'] ?? 0);
$q = trim($_GET['q'] ?? '');

$params = [];
$where = "1=1";

if ($buildingId > 0) {
  $where .= " AND u.building_id=?";
  $params[] = $buildingId;
}

if ($q !== '') {
  $where .= " AND (u.unit_code LIKE ? OR b.name LIKE ?)";
  $params[] = '%' . $q . '%';
  $params[] = '%' . $q . '%';
}

// Buildings dropdown
$buildings = [];
try {
  $buildings = db()->query("SELECT id, name FROM buildings ORDER BY name ASC")->fetchAll();
} catch (Throwable $e) {}

// Units list
$rows = [];
try {
  $stmt = db()->prepare("
    SELECT u.id, u.unit_code, u.status, u.floor, u.qr_token,
           b.name AS building_name
    FROM units u
    JOIN buildings b ON b.id = u.building_id
    WHERE {$where}
    ORDER BY b.name ASC, u.unit_code ASC
    LIMIT 500
  ");
  $stmt->execute($params);
  $rows = $stmt->fetchAll();
} catch (Throwable $e) {}
?>

<div class="container mb-3">
  <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
    <div>
      <h5 class="page-title mb-1">Units</h5>
      <div class="text-muted small">View unit profiles, inspections, and laundry.</div>
    </div>

    <div class="d-flex gap-2 flex-wrap">
      <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/dashboard.php">Dashboard</a>
      <?php if (!$isAdmin): ?>
        <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/staff_dashboard.php">Staff Dashboard</a>
      <?php endif; ?>
      <?php if ($isAdmin): ?>
        <a class="btn btn-primary" href="<?= BASE_URL ?>/admin_add_unit.php">Add Unit</a>
      <?php endif; ?>
    </div>
  </div>
</div>

<div class="container">

  <div class="card p-4 mb-3">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-4">
        <label class="form-label">Building</label>
        <select name="building_id" class="form-select">
          <option value="0">All buildings</option>
          <?php foreach ($buildings as $b): ?>
            <option value="<?= (int)$b['id'] ?>" <?= $buildingId === (int)$b['id'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($b['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-md-5">
        <label class="form-label">Search</label>
        <input class="form-control" name="q" value="<?= htmlspecialchars($q) ?>" placeholder="Unit code or building name">
      </div>

      <div class="col-md-3 d-flex gap-2">
        <button class="btn btn-primary w-100">Filter</button>
        <a class="btn btn-outline-secondary w-100" href="<?= BASE_URL ?>/units_list.php">Reset</a>
      </div>
    </form>
  </div>

  <div class="card p-4">
    <?php if (!$rows): ?>
      <div class="text-muted">No units found.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead>
            <tr>
              <th>Building</th>
              <th>Unit</th>
              <th>Status</th>
              <th>Floor</th>
              <th style="min-width:320px;">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td><?= htmlspecialchars($r['building_name'] ?? '') ?></td>
                <td class="fw-semibold"><?= htmlspecialchars($r['unit_code'] ?? '') ?></td>
                <td><span class="badge bg-light text-dark"><?= htmlspecialchars($r['status'] ?? '') ?></span></td>
                <td><?= htmlspecialchars($r['floor'] ?? '') ?></td>
                <td class="d-flex gap-2 flex-wrap">

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

                  <a class="btn btn-sm btn-outline-secondary"
                     href="<?= BASE_URL ?>/unit_inspections.php?unit_id=<?= (int)$r['id'] ?>">
                    Inspections
                  </a>

                  <a class="btn btn-sm btn-outline-secondary"
                     href="<?= BASE_URL ?>/unit_laundry.php?unit_id=<?= (int)$r['id'] ?>">
                    Laundry Bags
                  </a>

                  <?php if ($isAdmin): ?>
                    <a class="btn btn-sm btn-outline-dark"
                       href="<?= BASE_URL ?>/unit_qr.php?id=<?= (int)$r['id'] ?>">
                      QR
                    </a>
                  <?php endif; ?>

                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>

</div>

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