<?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/LaundryBag.php';

require_login();

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

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

/**
 * Counts / summary:
 * - People = active tenants
 * - Beds = sum inventory where item_name contains 'bed'
 * - Total items = sum inventory quantities
 */
$peopleStmt = db()->prepare("SELECT COUNT(*) AS c FROM tenants WHERE unit_id=? AND is_active=1");
$peopleStmt->execute([$unitId]);
$peopleCount = (int)($peopleStmt->fetch()['c'] ?? 0);

$bedsStmt = db()->prepare("SELECT COALESCE(SUM(quantity),0) AS c FROM inventory_items WHERE unit_id=? AND LOWER(item_name) LIKE '%bed%'");
$bedsStmt->execute([$unitId]);
$bedsCount = (int)($bedsStmt->fetch()['c'] ?? 0);

$totalItemsStmt = db()->prepare("SELECT COALESCE(SUM(quantity),0) AS c FROM inventory_items WHERE unit_id=?");
$totalItemsStmt->execute([$unitId]);
$totalItems = (int)($totalItemsStmt->fetch()['c'] ?? 0);

// Tenants preview list
$tenantsStmt = db()->prepare("SELECT id, full_name, is_active FROM tenants WHERE unit_id=? ORDER BY is_active DESC, full_name ASC LIMIT 5");
$tenantsStmt->execute([$unitId]);
$tenants = $tenantsStmt->fetchAll();

// Inventory preview list
$itemsStmt = db()->prepare("SELECT id, item_name, quantity FROM inventory_items WHERE unit_id=? ORDER BY item_name ASC LIMIT 5");
$itemsStmt->execute([$unitId]);
$items = $itemsStmt->fetchAll();

/**
 * ✅ Laundry bag summary (1 bag per unit; bag can contain multiple item types)
 */
$bag = null;
$bagItemsByType = [];

$itemLabels = [
  'bedsheet'   => 'Bedsheet',
  'pillowcase' => 'Pillow Case',
  'towel'      => 'Towel',
  'doormat'    => 'Door Mat',
];

try {
  $bag = LaundryBag::getByUnit($unitId);
  if ($bag) {
    $bagItems = LaundryBag::items((int)$bag['id']);
    foreach ($bagItems as $it) $bagItemsByType[$it['item_type']] = $it;
  }
} catch (Throwable $e) {
  $bag = null;
  $bagItemsByType = [];
}

function laundryBadge(string $status): string {
  $s = strtolower($status);
  return match($s) {
    'clean' => 'text-bg-success',
    'dirty' => 'text-bg-danger',
    'delivered' => 'text-bg-primary',
    'picked_up' => 'text-bg-warning',
    default => 'text-bg-secondary',
  };
}

function laundryText(string $status): string {
  return ucwords(str_replace('_',' ', strtolower($status)));
}

$pageTitle = 'Unit ' . $unit['unit_code'];
require_once __DIR__ . '/../app/views/partials/header.php';
?>

<!-- Breadcrumb -->
<div class="container mb-3">
  <nav aria-label="breadcrumb">
    <ol class="breadcrumb mb-0">
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/dashboard.php">Dashboard</a></li>
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/units_list.php">Units</a></li>
      <li class="breadcrumb-item active" aria-current="page">
        Unit <?= htmlspecialchars($unit['unit_code']) ?>
      </li>
    </ol>
  </nav>
</div>

<div class="container">


  <!-- Unit header card -->
  <div class="card p-4 mb-3">
    <div class="d-flex justify-content-between flex-wrap gap-2">
      <div>
        <h4 class="mb-1"><?= htmlspecialchars($unit['unit_code']) ?></h4>

        <div class="text-muted">
          <?= htmlspecialchars($unit['building_name']) ?> • <?= htmlspecialchars($unit['floor'] ?? '') ?>

          <?php if (!empty($unit['building_address'])): ?>
            <div class="small mt-1">📍 <?= htmlspecialchars($unit['building_address']) ?></div>
          <?php endif; ?>
        </div>
      </div>

      <div>
        <span class="badge badge-soft"><?= htmlspecialchars($unit['status']) ?></span>
      </div>
    </div>

    <hr>

    <a class="btn btn-outline-primary w-100 mb-3"
       href="<?= BASE_URL ?>/unit_inspections.php?unit_id=<?= (int)$unitId ?>">
      View Inspection History
    </a>

    <a class="btn btn-outline-primary w-100 mb-3"
       href="<?= BASE_URL ?>/unit_laundry.php?unit_id=<?= (int)$unit['id'] ?>">
      Laundry Bag (Manage)
    </a>

    <!-- ✅ Laundry Bag Summary -->
    <div class="card p-3 mb-3">
      <div class="d-flex justify-content-between align-items-center">
        <div class="fw-semibold">Laundry Bag Status</div>
        <a class="small" href="<?= BASE_URL ?>/unit_laundry.php?unit_id=<?= (int)$unitId ?>">Manage</a>
      </div>

      <?php if (!$bag): ?>
        <div class="text-muted small mt-2">
          No laundry bag set for this unit yet.
        </div>
      <?php else: ?>
        <div class="text-muted small mt-2">
          Bag #: <strong><?= htmlspecialchars($bag['bag_number']) ?></strong>
          <?php if (!empty($bag['updated_at'])): ?>
            • Updated: <?= htmlspecialchars($bag['updated_at']) ?>
          <?php endif; ?>
        </div>

        <div class="row g-2 mt-2">
          <?php foreach ($itemLabels as $key => $label): ?>
            <?php
              $row = $bagItemsByType[$key] ?? null;
              if (!$row) continue; // show only included items
              $status = $row['status'] ?? 'dirty';
            ?>
            <div class="col-md-6">
              <div class="d-flex justify-content-between align-items-center border rounded p-2">
                <div class="fw-semibold"><?= htmlspecialchars($label) ?></div>
                <span class="badge <?= htmlspecialchars(laundryBadge($status)) ?>">
                  <?= htmlspecialchars(laundryText($status)) ?>
                </span>
              </div>
            </div>
          <?php endforeach; ?>
        </div>

        <?php if (empty($bagItemsByType)): ?>
          <div class="text-muted small mt-2">
            Bag exists, but no items are selected inside it yet.
          </div>
        <?php endif; ?>
      <?php endif; ?>
    </div>

    <div class="row g-3">
      <div class="col-md-4">
        <div class="card p-3 h-100">
          <div class="text-muted small">People Residing (Active Tenants)</div>
          <div class="fs-2 fw-semibold"><?= $peopleCount ?></div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card p-3 h-100">
          <div class="text-muted small">Beds (from inventory)</div>
          <div class="fs-2 fw-semibold"><?= $bedsCount ?></div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card p-3 h-100">
          <div class="text-muted small">Total Furniture/Items</div>
          <div class="fs-2 fw-semibold"><?= $totalItems ?></div>
        </div>
      </div>
    </div>
  </div>

  <!-- Tenants section -->
  <div class="card p-4 mb-3">
    <div class="d-flex justify-content-between align-items-center mb-2">
      <h6 class="mb-0">Tenants</h6>
      <a class="btn btn-sm btn-primary"
         href="<?= BASE_URL ?>/unit_tenants.php?unit_id=<?= (int)$unitId ?>">
        Manage Tenants
      </a>
    </div>

    <?php if (!$tenants): ?>
      <div class="text-muted">No tenants added yet.</div>
    <?php else: ?>
      <ul class="list-group list-group-flush">
        <?php foreach ($tenants as $t): ?>
          <li class="list-group-item d-flex justify-content-between align-items-center">
            <div><?= htmlspecialchars($t['full_name']) ?></div>
            <?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; ?>
          </li>
        <?php endforeach; ?>
      </ul>
      <div class="small text-muted mt-2">Showing up to 5 tenants.</div>
    <?php endif; ?>
  </div>

  <!-- Inventory section -->
  <div class="card p-4 mb-3">
    <div class="d-flex justify-content-between align-items-center mb-2">
      <h6 class="mb-0">Beds & Furniture</h6>
      <a class="btn btn-sm btn-primary"
         href="<?= BASE_URL ?>/unit_inventory.php?unit_id=<?= (int)$unitId ?>">
        Manage Items
      </a>
    </div>

    <?php if (!$items): ?>
      <div class="text-muted">No items added yet.</div>
    <?php else: ?>
      <ul class="list-group list-group-flush">
        <?php foreach ($items as $it): ?>
          <li class="list-group-item d-flex justify-content-between align-items-center">
            <div><?= htmlspecialchars($it['item_name']) ?></div>
            <span class="badge badge-soft"><?= (int)$it['quantity'] ?></span>
          </li>
        <?php endforeach; ?>
      </ul>
      <div class="small text-muted mt-2">Showing up to 5 items.</div>
    <?php endif; ?>
  </div>

</div>

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