<?php use App\Helpers\Helper; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="admin-page-title mb-1">Buildings</h1>
    <p class="text-muted small mb-0">Manage buildings across all properties</p>
  </div>
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addBuildingModal">
    <i class="bi bi-plus-lg me-2"></i>Add Building
  </button>
</div>

<!-- Stats Row -->
<div class="row g-3 mb-4">
  <div class="col-md-3">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap blue"><i class="bi bi-buildings"></i></div>
      <div><div class="stat-val"><?= count($buildings) ?></div><div class="stat-lbl">Total Buildings</div></div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap green"><i class="bi bi-check-circle"></i></div>
      <div><div class="stat-val"><?= count(array_filter($buildings, fn($b)=>$b['status']==='active')) ?></div><div class="stat-lbl">Active</div></div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap orange"><i class="bi bi-door-open"></i></div>
      <div><div class="stat-val"><?= array_sum(array_column($buildings,'unit_count')) ?></div><div class="stat-lbl">Total Units</div></div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="admin-stat-card">
      <div class="stat-icon-wrap purple"><i class="bi bi-house-door"></i></div>
      <div><div class="stat-val"><?= count(array_unique(array_column($buildings,'property_name'))) ?></div><div class="stat-lbl">Properties</div></div>
    </div>
  </div>
</div>

<!-- Search & Filter Bar -->
<div class="data-card mb-4">
  <div class="data-card-header">
    <h6><i class="bi bi-buildings me-2 text-primary"></i>All Buildings</h6>
    <div class="d-flex gap-2">
      <input type="text" id="buildingSearch" class="form-control form-control-sm" style="width:200px" placeholder="Search buildings...">
      <select id="filterProperty" class="form-select form-select-sm" style="width:180px">
        <option value="">All Properties</option>
        <?php foreach ($properties as $p): ?>
        <option value="<?= Helper::e($p['name']) ?>"><?= Helper::e($p['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
  </div>
</div>

<!-- Building Cards Grid -->
<?php if (empty($buildings)): ?>
<div class="text-center py-5 text-muted">
  <i class="bi bi-buildings" style="font-size:4rem;opacity:0.3"></i>
  <h5 class="mt-3 fw-700">No Buildings Yet</h5>
  <p class="small">Click "Add Building" to get started.</p>
</div>
<?php else: ?>
<div class="row g-3" id="buildingGrid">
  <?php foreach ($buildings as $b): ?>
  <div class="col-xl-4 col-lg-6 building-card-wrap" data-name="<?= strtolower(Helper::e($b['name'])) ?>" data-property="<?= Helper::e($b['property_name']) ?>">
    <div class="building-card h-100">
      <!-- Card Top -->
      <div class="building-card-top">
        <div class="d-flex align-items-center gap-3">
          <div class="building-icon-box">
            <i class="bi bi-building-fill"></i>
            <span class="building-floor-badge"><?= $b['floors'] ?>F</span>
          </div>
          <div class="flex-grow-1 min-w-0">
            <div class="fw-700 fs-6 text-truncate"><?= Helper::e($b['name']) ?></div>
            <?php if ($b['code']): ?>
            <code class="building-code"><?= Helper::e($b['code']) ?></code>
            <?php endif; ?>
          </div>
          <?= Helper::statusBadge($b['status']) ?>
        </div>
      </div>
      <!-- Card Body -->
      <div class="building-card-body">
        <div class="building-prop-tag">
          <i class="bi bi-geo-alt-fill me-1"></i><?= Helper::e($b['property_name']) ?>
        </div>
        <?php if ($b['description']): ?>
        <p class="building-desc"><?= Helper::e(substr($b['description'],0,70)) ?><?= strlen($b['description'])>70?'...':'' ?></p>
        <?php endif; ?>
        <!-- Stats Row -->
        <div class="building-stats">
          <div class="building-stat">
            <i class="bi bi-door-open text-primary"></i>
            <span class="fw-700"><?= $b['unit_count'] ?></span>
            <span>Units</span>
          </div>
          <div class="building-stat">
            <i class="bi bi-layers text-primary"></i>
            <span class="fw-700"><?= $b['floors'] ?></span>
            <span>Floors</span>
          </div>
        </div>
      </div>
      <!-- Card Footer Actions -->
      <div class="building-card-footer">
        <a href="<?= APP_URL ?>/admin/units?building_id=<?= $b['id'] ?>" class="btn btn-sm btn-outline-primary flex-grow-1">
          <i class="bi bi-door-open me-1"></i>View Units
        </a>
        <button class="btn btn-sm btn-outline-secondary"
          data-bs-toggle="modal" data-bs-target="#editBuildingModal"
          data-id="<?= $b['id'] ?>"
          data-name="<?= Helper::e($b['name']) ?>"
          data-code="<?= Helper::e($b['code']??'') ?>"
          data-floors="<?= $b['floors'] ?>"
          data-property="<?= $b['property_id'] ?>"
          data-status="<?= $b['status'] ?>"
          data-desc="<?= Helper::e($b['description']??'') ?>"
          title="Edit">
          <i class="bi bi-pencil"></i>
        </button>
        <form method="POST" action="<?= APP_URL ?>/admin/buildings/<?= $b['id'] ?>/delete" class="d-inline"
          onsubmit="return confirm('Delete <?= Helper::e($b['name']) ?>?')">
          <?= Helper::csrf() ?>
          <button class="btn btn-sm btn-outline-danger" title="Delete"><i class="bi bi-trash"></i></button>
        </form>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<style>
.building-card {
  background: #fff;
  border-radius: 16px;
  border: 1px solid #e2e8f0;
  overflow: hidden;
  transition: all 0.25s ease;
  display: flex;
  flex-direction: column;
}
.building-card:hover {
  box-shadow: 0 8px 32px rgba(26,60,94,0.12);
  transform: translateY(-3px);
  border-color: #1a3c5e30;
}
.building-card-top {
  padding: 1.25rem 1.25rem 1rem;
  border-bottom: 1px solid #f1f5f9;
}
.building-icon-box {
  width: 52px; height: 52px;
  background: linear-gradient(135deg, #1a3c5e, #2d6a9f);
  border-radius: 14px;
  display: flex; align-items: center; justify-content: center;
  color: #fff; font-size: 1.4rem;
  flex-shrink: 0;
  position: relative;
}
.building-floor-badge {
  position: absolute;
  bottom: -6px; right: -6px;
  background: #e8a020;
  color: #fff;
  font-size: 0.6rem;
  font-weight: 700;
  padding: 2px 5px;
  border-radius: 6px;
  border: 2px solid #fff;
}
.building-code {
  font-size: 0.72rem;
  background: #f1f5f9;
  padding: 2px 6px;
  border-radius: 5px;
  color: #475569;
}
.building-card-body {
  padding: 1rem 1.25rem;
  flex: 1;
}
.building-prop-tag {
  display: inline-flex;
  align-items: center;
  background: #eff6ff;
  color: #1a3c5e;
  font-size: 0.78rem;
  font-weight: 600;
  padding: 4px 10px;
  border-radius: 20px;
  margin-bottom: 0.6rem;
}
.building-desc {
  font-size: 0.82rem;
  color: #64748b;
  margin-bottom: 0.75rem;
  line-height: 1.5;
}
.building-stats {
  display: flex;
  gap: 1.5rem;
  padding-top: 0.75rem;
  border-top: 1px solid #f1f5f9;
}
.building-stat {
  display: flex;
  align-items: center;
  gap: 0.35rem;
  font-size: 0.82rem;
  color: #64748b;
}
.building-stat .fw-700 { color: #1e293b; font-size: 0.95rem; }
.building-card-footer {
  padding: 0.85rem 1.25rem;
  border-top: 1px solid #f1f5f9;
  background: #f8fafc;
  display: flex;
  gap: 0.5rem;
  align-items: center;
}
</style>

<script>
function filterBuildings() {
  const q = document.getElementById('buildingSearch').value.toLowerCase();
  const prop = document.getElementById('filterProperty').value.toLowerCase();
  document.querySelectorAll('.building-card-wrap').forEach(card => {
    const nameMatch = card.dataset.name.includes(q);
    const propMatch = !prop || card.dataset.property.toLowerCase() === prop;
    card.style.display = (nameMatch && propMatch) ? '' : 'none';
  });
}
document.getElementById('buildingSearch').addEventListener('input', filterBuildings);
document.getElementById('filterProperty').addEventListener('change', filterBuildings);

document.querySelectorAll('[data-bs-target="#editBuildingModal"]').forEach(btn => {
  btn.addEventListener('click', function() {
    const id = this.dataset.id;
    document.getElementById('editBuildingForm').action = '<?= APP_URL ?>/admin/buildings/' + id + '/edit';
    document.getElementById('edit_name').value        = this.dataset.name;
    document.getElementById('edit_code').value        = this.dataset.code;
    document.getElementById('edit_floors').value      = this.dataset.floors;
    document.getElementById('edit_desc').value        = this.dataset.desc;
    document.getElementById('edit_status').value      = this.dataset.status;
    document.getElementById('edit_property_id').value = this.dataset.property;
  });
});
</script>

<!-- Add Building Modal -->
<div class="modal fade" id="addBuildingModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header" style="background:linear-gradient(135deg,#1a3c5e,#2d6a9f);color:#fff">
        <h5 class="modal-title fw-700"><i class="bi bi-buildings me-2"></i>Add New Building</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?= APP_URL ?>/admin/buildings">
        <?= Helper::csrf() ?>
        <div class="modal-body p-4">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-600">Property <span class="text-danger">*</span></label>
              <select name="property_id" class="form-select" required>
                <option value="">— Select Property —</option>
                <?php foreach ($properties as $p): ?>
                <option value="<?= $p['id'] ?>"><?= Helper::e($p['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Building Name <span class="text-danger">*</span></label>
              <input type="text" name="name" class="form-control" required placeholder="e.g. Block A">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-600">Building Code</label>
              <input type="text" name="code" class="form-control" placeholder="e.g. BLK-A">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-600">Number of Floors <span class="text-danger">*</span></label>
              <input type="number" name="floors" class="form-control" value="1" min="1" max="50" required>
            </div>
            <div class="col-md-4">
              <label class="form-label fw-600">Status</label>
              <select name="status" class="form-select">
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
                <option value="under_construction">Under Construction</option>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label fw-600">Description</label>
              <textarea name="description" class="form-control" rows="2" placeholder="Optional description..."></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer bg-light">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary px-4"><i class="bi bi-save me-2"></i>Save Building</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Building Modal -->
<div class="modal fade" id="editBuildingModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header" style="background:linear-gradient(135deg,#1a3c5e,#2d6a9f);color:#fff">
        <h5 class="modal-title fw-700"><i class="bi bi-pencil me-2"></i>Edit Building</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" id="editBuildingForm">
        <?= Helper::csrf() ?>
        <input type="hidden" name="_method" value="PUT">
        <div class="modal-body p-4">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-600">Property <span class="text-danger">*</span></label>
              <select name="property_id" id="edit_property_id" class="form-select" required>
                <?php foreach ($properties as $p): ?>
                <option value="<?= $p['id'] ?>"><?= Helper::e($p['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Building Name <span class="text-danger">*</span></label>
              <input type="text" name="name" id="edit_name" class="form-control" required>
            </div>
            <div class="col-md-4">
              <label class="form-label fw-600">Building Code</label>
              <input type="text" name="code" id="edit_code" class="form-control">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-600">Number of Floors</label>
              <input type="number" name="floors" id="edit_floors" class="form-control" min="1" max="50">
            </div>
            <div class="col-md-4">
              <label class="form-label fw-600">Status</label>
              <select name="status" id="edit_status" class="form-select">
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
                <option value="under_construction">Under Construction</option>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label fw-600">Description</label>
              <textarea name="description" id="edit_desc" class="form-control" rows="2"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer bg-light">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary px-4"><i class="bi bi-save me-2"></i>Update Building</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
// Populate edit modal
document.querySelectorAll('[data-bs-target="#editBuildingModal"]').forEach(btn => {
  btn.addEventListener('click', function() {
    const id = this.dataset.id;
    document.getElementById('editBuildingForm').action = '<?= APP_URL ?>/admin/buildings/' + id + '/edit';
    document.getElementById('edit_name').value      = this.dataset.name;
    document.getElementById('edit_code').value      = this.dataset.code;
    document.getElementById('edit_floors').value    = this.dataset.floors;
    document.getElementById('edit_desc').value      = this.dataset.desc;
    document.getElementById('edit_status').value    = this.dataset.status;
    document.getElementById('edit_property_id').value = this.dataset.property;
  });
});

// Live search
document.getElementById('buildingSearch').addEventListener('input', function() {
  const q = this.value.toLowerCase();
  document.querySelectorAll('#buildingTable tbody tr').forEach(row => {
    row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
});
</script>
