<?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">Units & Rooms</h1>
    <p class="text-muted small mb-0">Manage all units across properties and buildings</p>
  </div>
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUnitModal">
    <i class="bi bi-plus-lg me-2"></i>Add Unit
  </button>
</div>

<!-- Stats -->
<div class="row g-3 mb-4">
  <?php
  $total     = count($units);
  $available = count(array_filter($units, fn($u)=>$u['status']==='available'));
  $occupied  = count(array_filter($units, fn($u)=>$u['status']==='occupied'));
  $maintenance = count(array_filter($units, fn($u)=>$u['status']==='maintenance'));
  ?>
  <div class="col-md-3"><div class="admin-stat-card"><div class="stat-icon-wrap blue"><i class="bi bi-door-closed"></i></div><div><div class="stat-val"><?= $total ?></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 green"><i class="bi bi-door-open"></i></div><div><div class="stat-val"><?= $available ?></div><div class="stat-lbl">Available</div></div></div></div>
  <div class="col-md-3"><div class="admin-stat-card"><div class="stat-icon-wrap orange"><i class="bi bi-person-check"></i></div><div><div class="stat-val"><?= $occupied ?></div><div class="stat-lbl">Occupied</div></div></div></div>
  <div class="col-md-3"><div class="admin-stat-card"><div class="stat-icon-wrap red"><i class="bi bi-tools"></i></div><div><div class="stat-val"><?= $maintenance ?></div><div class="stat-lbl">Maintenance</div></div></div></div>
</div>

<!-- Filters -->
<div class="data-card mb-4">
  <div class="data-card-header">
    <h6><i class="bi bi-funnel me-2 text-primary"></i>Filter Units</h6>
  </div>
  <div class="p-3">
    <form method="GET" action="<?= APP_URL ?>/admin/units" class="row g-2 align-items-end">
      <div class="col-md-3">
        <label class="form-label fw-600 small">Property</label>
        <select name="property_id" class="form-select form-select-sm">
          <option value="">All Properties</option>
          <?php foreach ($properties as $p): ?>
          <option value="<?= $p['id'] ?>" <?= $propId==$p['id']?'selected':'' ?>><?= Helper::e($p['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label fw-600 small">Status</label>
        <select name="status" class="form-select form-select-sm">
          <option value="">All Statuses</option>
          <?php foreach (['available','occupied','maintenance','inactive'] as $s): ?>
          <option value="<?= $s ?>" <?= $status===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-search me-1"></i>Filter</button>
      </div>
      <div class="col-md-2">
        <a href="<?= APP_URL ?>/admin/units" class="btn btn-outline-secondary btn-sm w-100"><i class="bi bi-x me-1"></i>Clear</a>
      </div>
      <div class="col-md-2">
        <input type="text" id="unitSearch" class="form-control form-control-sm" placeholder="Search units...">
      </div>
    </form>
  </div>
</div>

<!-- Units Table -->
<div class="data-card">
  <div class="data-card-header">
    <h6><i class="bi bi-door-closed me-2 text-primary"></i>Units List <span class="badge bg-primary ms-2"><?= $total ?></span></h6>
  </div>
  <div class="table-responsive">
    <table class="table mb-0" id="unitsTable">
      <thead>
        <tr>
          <th>Unit</th>
          <th>Building / Property</th>
          <th>Type</th>
          <th>Specs</th>
          <th>Rent</th>
          <th>Tenant</th>
          <th>Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($units as $u): ?>
        <tr>
          <td>
            <div class="fw-700"><?= Helper::e($u['unit_number']) ?></div>
            <div class="text-muted" style="font-size:0.75rem"><code><?= Helper::e($u['unit_code']??'') ?></code></div>
            <div class="text-muted" style="font-size:0.75rem">Floor <?= $u['floor'] ?></div>
          </td>
          <td>
            <div class="fw-600 small"><?= Helper::e($u['building_name']) ?></div>
            <div class="text-muted" style="font-size:0.75rem"><?= Helper::e($u['property_name']) ?></div>
          </td>
          <td><span class="badge bg-light text-dark"><?= ucfirst($u['unit_type']??'apartment') ?></span></td>
          <td>
            <div class="d-flex gap-1 flex-wrap">
              <span class="badge bg-primary text-white"><i class="bi bi-door-open me-1"></i><?= $u['bedrooms'] ?>bd</span>
              <span class="badge bg-info text-white"><i class="bi bi-droplet me-1"></i><?= $u['bathrooms'] ?>ba</span>
              <?php if ($u['is_furnished']): ?><span class="badge bg-success text-white">Furnished</span><?php endif; ?>
              <?php if ($u['has_parking']): ?><span class="badge bg-warning text-white"><i class="bi bi-car-front me-1"></i>Parking</span><?php endif; ?>
              <?php if ($u['has_wifi']): ?><span class="badge bg-secondary text-white"><i class="bi bi-wifi me-1"></i>WiFi</span><?php endif; ?>
            </div>
          </td>
          <td>
            <?php
              $period = $u['rent_period'] ?? 'monthly';
              $rentAmt = match($period) {
                'daily'  => $u['daily_rent'] ?? $u['monthly_rent'],
                'weekly' => $u['weekly_rent'] ?? $u['monthly_rent'],
                default  => $u['monthly_rent'],
              };
              $periodLabel = match($period) { 'daily'=>'/day','weekly'=>'/week', default=>'/month' };
            ?>
            <div class="fw-700 text-primary"><?= Helper::money($rentAmt) ?></div>
            <div>
              <span class="badge bg-<?= $period==='daily'?'danger':($period==='weekly'?'warning':'success') ?> text-white" style="font-size:0.7rem"><?= $periodLabel ?></span>
            </div>
          </td>
          <td>
            <?php if ($u['current_tenant']): ?>
            <div class="d-flex align-items-center gap-2">
              <div class="avatar-xs bg-primary rounded-circle d-flex align-items-center justify-content-center text-white fw-700"><?= strtoupper(substr($u['current_tenant'],0,1)) ?></div>
              <span class="small fw-600"><?= Helper::e($u['current_tenant']) ?></span>
            </div>
            <?php else: ?>
            <span class="text-muted small">—</span>
            <?php endif; ?>
          </td>
          <td><?= Helper::statusBadge($u['status']) ?></td>
          <td>
            <div class="d-flex gap-1">
              <a href="<?= APP_URL ?>/admin/units/<?= $u['id'] ?>/edit" class="btn btn-action btn-outline-primary" title="Edit"><i class="bi bi-pencil"></i></a>
              <form method="POST" action="<?= APP_URL ?>/admin/units/<?= $u['id'] ?>/delete" class="d-inline" onsubmit="return confirm('Delete unit <?= Helper::e($u['unit_number']) ?>?')">
                <?= Helper::csrf() ?>
                <button class="btn btn-action btn-outline-danger" title="Delete"><i class="bi bi-trash"></i></button>
              </form>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($units)): ?>
        <tr><td colspan="8" class="text-center text-muted py-5">
          <i class="bi bi-door-closed fs-1 d-block mb-2 opacity-25"></i>No units found. Add your first unit.
        </td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Add Unit Modal -->
<div class="modal fade" id="addUnitModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <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-door-open me-2"></i>Add New Unit</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?= APP_URL ?>/admin/units">
        <?= Helper::csrf() ?>
        <div class="modal-body p-4">
          <div class="row g-3">
            <!-- Building & Unit Info -->
            <div class="col-12"><div class="form-section-title">Location</div></div>
            <div class="col-md-4">
              <label class="form-label fw-600">Property <span class="text-danger">*</span></label>
              <select id="add_property_filter" class="form-select">
                <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-4">
              <label class="form-label fw-600">Building <span class="text-danger">*</span></label>
              <select name="building_id" id="add_building_id" class="form-select" required>
                <option value="">— Select Building —</option>
                <?php foreach ($buildings as $b): ?>
                <option value="<?= $b['id'] ?>" data-property="<?= $b['property_id'] ?>"><?= Helper::e($b['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-2">
              <label class="form-label fw-600">Unit Number <span class="text-danger">*</span></label>
              <input type="text" name="unit_number" class="form-control" required placeholder="e.g. A101">
            </div>
            <div class="col-md-2">
              <label class="form-label fw-600">Floor <span class="text-danger">*</span></label>
              <input type="number" name="floor" class="form-control" value="1" min="0" max="50" required>
            </div>

            <!-- Unit Details -->
            <div class="col-12"><div class="form-section-title mt-2">Unit Details</div></div>
            <div class="col-md-3">
              <label class="form-label fw-600">Unit Type</label>
              <select name="unit_type" class="form-select">
                <?php foreach (['apartment','studio','villa','room','office','shop'] as $t): ?>
                <option value="<?= $t ?>"><?= ucfirst($t) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-2">
              <label class="form-label fw-600">Bedrooms</label>
              <input type="number" name="bedrooms" class="form-control" value="1" min="0" max="10">
            </div>
            <div class="col-md-2">
              <label class="form-label fw-600">Bathrooms</label>
              <input type="number" name="bathrooms" class="form-control" value="1" min="1" max="10">
            </div>
            <div class="col-md-2">
              <label class="form-label fw-600">Size (m²)</label>
              <input type="number" name="floor_size" class="form-control" placeholder="e.g. 45">
            </div>
            <div class="col-md-3">
              <label class="form-label fw-600">Rent Period <span class="text-danger">*</span></label>
              <select name="rent_period" id="add_rent_period" class="form-select" onchange="toggleRentFields('add')">
                <option value="monthly">Monthly</option>
                <option value="weekly">Weekly</option>
                <option value="daily">Daily</option>
              </select>
            </div>
            <div class="col-md-3" id="add_monthly_wrap">
              <label class="form-label fw-600">Monthly Rent (TZS) <span class="text-danger">*</span></label>
              <input type="number" name="monthly_rent" id="add_monthly_rent" class="form-control" placeholder="e.g. 500000">
            </div>
            <div class="col-md-3" id="add_weekly_wrap" style="display:none">
              <label class="form-label fw-600">Weekly Rent (TZS) <span class="text-danger">*</span></label>
              <input type="number" name="weekly_rent" id="add_weekly_rent" class="form-control" placeholder="e.g. 150000">
            </div>
            <div class="col-md-3" id="add_daily_wrap" style="display:none">
              <label class="form-label fw-600">Daily Rent (TZS) <span class="text-danger">*</span></label>
              <input type="number" name="daily_rent" id="add_daily_rent" class="form-control" placeholder="e.g. 25000">
            </div>
            <div class="col-md-3">
              <label class="form-label fw-600">Security Deposit (TZS)</label>
              <input type="number" name="security_deposit" class="form-control" placeholder="e.g. 1000000">
            </div>

            <!-- Amenities -->
            <div class="col-12"><div class="form-section-title mt-2">Amenities</div></div>
            <div class="col-12">
              <div class="d-flex gap-4 flex-wrap">
                <?php foreach ([
                  ['is_furnished','Furnished'],['has_parking','Parking'],
                  ['has_wifi','WiFi'],['has_ac','Air Conditioning'],['pets_allowed','Pets Allowed']
                ] as [$name,$label]): ?>
                <div class="form-check form-switch">
                  <input class="form-check-input" type="checkbox" name="<?= $name ?>" id="add_<?= $name ?>" value="1">
                  <label class="form-check-label fw-600 small" for="add_<?= $name ?>"><?= $label ?></label>
                </div>
                <?php endforeach; ?>
              </div>
            </div>
            <div class="col-12">
              <label class="form-label fw-600">Description</label>
              <textarea name="description" class="form-control" rows="2" placeholder="Optional notes about this unit..."></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 Unit</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function toggleRentFields(prefix) {
  const period = document.getElementById(prefix + '_rent_period').value;
  document.getElementById(prefix + '_monthly_wrap').style.display = period === 'monthly' ? '' : 'none';
  document.getElementById(prefix + '_weekly_wrap').style.display  = period === 'weekly'  ? '' : 'none';
  document.getElementById(prefix + '_daily_wrap').style.display   = period === 'daily'   ? '' : 'none';
  // Toggle required
  document.getElementById(prefix + '_monthly_rent') && (document.getElementById(prefix + '_monthly_rent').required = period === 'monthly');
  document.getElementById(prefix + '_weekly_rent')  && (document.getElementById(prefix + '_weekly_rent').required  = period === 'weekly');
  document.getElementById(prefix + '_daily_rent')   && (document.getElementById(prefix + '_daily_rent').required   = period === 'daily');
}

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

// Filter buildings by property in add modal
document.getElementById('add_property_filter').addEventListener('change', function() {
  const propId = this.value;
  const buildSel = document.getElementById('add_building_id');
  buildSel.querySelectorAll('option').forEach(opt => {
    if (!opt.value) { opt.style.display = ''; return; }
    opt.style.display = (!propId || opt.dataset.property === propId) ? '' : 'none';
  });
  buildSel.value = '';
});
</script>
