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

require_login();
$user = current_user();

// ✅ Staff goes to staff dashboard
if (($user['role'] ?? '') === 'staff') {
  header('Location: ' . BASE_URL . '/staff_dashboard.php');
  exit;
}

// Simple counts (safe if tables exist)
function safeCount(string $table): int {
  try {
    $stmt = db()->query("SELECT COUNT(*) AS c FROM {$table}");
    $row = $stmt->fetch();
    return (int)($row['c'] ?? 0);
  } catch (Throwable $e) {
    return 0;
  }
}

$buildingsCount   = safeCount('buildings');
$unitsCount       = safeCount('units');
$tenantsCount     = safeCount('tenants');
$inspectionsCount = safeCount('inspections');

// Notifications
$notifCount = Notification::unreadCount((int)$user['id']);
$notifs = Notification::unreadList((int)$user['id'], 10);

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

function notifLink(?string $link): string {
  $link = (string)$link;
  if ($link === '') return BASE_URL . '/dashboard.php';
  if (str_starts_with($link, 'http')) return $link;
  return BASE_URL . '/' . ltrim($link, '/');
}

function notifBadge(string $type): string {
  $type = strtolower(trim($type));
  return match ($type) {
    'inspection_submitted' => '<span class="badge text-bg-primary">INSPECTION</span>',
    'laundry_delivered'    => '<span class="badge text-bg-success">LAUNDRY</span>',
    'tenant_added'         => '<span class="badge text-bg-info">TENANT</span>',
    'unit_added'           => '<span class="badge text-bg-warning">UNIT</span>',
    default                => '<span class="badge text-bg-secondary">UPDATE</span>',
  };
}
?>

<div class="container">

  <div class="card p-4 mb-3">
    <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
      <div>
        <h5 class="page-title mb-1">Admin Dashboard</h5>
        <div class="text-muted"><?= htmlspecialchars($user['full_name']) ?></div>
      </div>
      <div>
        <span class="badge bg-light text-dark"><?= htmlspecialchars($user['role']) ?></span>
      </div>
    </div>
  </div>

  <!-- ✅ Notifications -->
  <div class="card p-4 mb-3">
    <div class="d-flex justify-content-between align-items-center gap-2 flex-wrap">
      <div>
        <h6 class="mb-1">Notifications</h6>
        <div class="text-muted small">
          You have <strong><?= (int)$notifCount ?></strong> unread notification(s).
        </div>
      </div>

      <div class="d-flex gap-2 flex-wrap">
        <a class="btn btn-sm btn-outline-secondary" href="<?= BASE_URL ?>/notifications.php">View all</a>

        <?php if ($notifCount > 0): ?>
          <form method="post" action="<?= BASE_URL ?>/notifications_mark_read.php" class="m-0">
            <input type="hidden" name="all" value="1">
            <button class="btn btn-sm btn-outline-secondary">Mark all as read</button>
          </form>
        <?php endif; ?>
      </div>
    </div>

    <hr>

    <?php if (!$notifs): ?>
      <div class="text-muted">No new notifications.</div>
    <?php else: ?>
      <div class="list-group">
        <?php foreach ($notifs as $n): ?>
          <?php
            $type = (string)($n['type'] ?? '');
            $title = (string)($n['title'] ?? '');
            $body = (string)($n['body'] ?? '');
            $createdAt = (string)($n['created_at'] ?? '');
          ?>
          <div class="list-group-item">
            <div class="d-flex justify-content-between gap-3 flex-wrap">

              <div style="min-width:260px;flex:1;">
                <div class="d-flex align-items-center gap-2 flex-wrap">
                  <?= notifBadge($type) ?>
                  <div class="fw-semibold"><?= htmlspecialchars($title) ?></div>
                </div>

                <?php if ($body !== ''): ?>
                  <div class="small text-muted mt-1">
                    <?= nl2br(htmlspecialchars($body)) ?>
                  </div>
                <?php endif; ?>

                <div class="small text-muted mt-2">
                  <?= htmlspecialchars($createdAt) ?>
                  <?php if (!empty($n['actor_name'])): ?>
                    • By <?= htmlspecialchars($n['actor_name']) ?>
                  <?php endif; ?>
                </div>

                <div class="mt-2 d-flex gap-2 flex-wrap">
                  <?php if (!empty($n['link_url'])): ?>
                    <a class="btn btn-sm btn-outline-primary" href="<?= htmlspecialchars(notifLink($n['link_url'])) ?>">
                      Open
                    </a>
                  <?php endif; ?>

                  <form method="post" action="<?= BASE_URL ?>/notifications_mark_read.php" class="m-0">
                    <input type="hidden" name="id" value="<?= (int)$n['id'] ?>">
                    <button class="btn btn-sm btn-outline-secondary">Mark read</button>
                  </form>
                </div>
              </div>

            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>

  <!-- Stats -->
  <div class="row g-3 mb-3">
    <div class="col-md-3">
      <div class="card p-3 h-100">
        <div class="text-muted small">Buildings</div>
        <div class="fs-3 fw-semibold"><?= $buildingsCount ?></div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card p-3 h-100">
        <div class="text-muted small">Units</div>
        <div class="fs-3 fw-semibold"><?= $unitsCount ?></div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card p-3 h-100">
        <div class="text-muted small">Tenants</div>
        <div class="fs-3 fw-semibold"><?= $tenantsCount ?></div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card p-3 h-100">
        <div class="text-muted small">Inspections</div>
        <div class="fs-3 fw-semibold"><?= $inspectionsCount ?></div>
      </div>
    </div>
  </div>

  <!-- Quick Actions -->
  <div class="row g-3">
    <div class="col-lg-6">
      <div class="card p-4 h-100">
        <h6 class="mb-3">Quick Actions</h6>

        <a href="<?= BASE_URL ?>/scan_camera.php" class="btn btn-primary w-100 mb-2">
          Scan QR (Start Inspection)
        </a>

        <a href="<?= BASE_URL ?>/units_list.php" class="btn btn-outline-primary w-100 mb-2">
          Units
        </a>

        <a href="<?= BASE_URL ?>/laundry_worklist.php" class="btn btn-outline-dark w-100 mb-2">
          Laundry Worklist
        </a>

        <a href="<?= BASE_URL ?>/laundry.php" class="btn btn-outline-dark w-100">
          Laundry Dashboard
        </a>
      </div>
    </div>

    <div class="col-lg-6">
      <div class="card p-4 h-100">
        <h6 class="mb-3">Admin</h6>

        <a href="<?= BASE_URL ?>/admin_users.php" class="btn btn-outline-primary w-100 mb-2">
          Manage Users
        </a>
        <a href="<?= BASE_URL ?>/admin_add_building.php" class="btn btn-outline-primary w-100 mb-2">
          Add Building
        </a>
        <a href="<?= BASE_URL ?>/admin_add_unit.php" class="btn btn-outline-primary w-100 mb-2">
          Add Unit (Generate QR)
        </a>
        <a href="<?= BASE_URL ?>/tenants_list.php" class="btn btn-outline-primary w-100 mb-2">
          Tenants
        </a>
        <a href="<?= BASE_URL ?>/audit_logs.php" class="btn btn-outline-secondary w-100">
          Audit Logs
        </a>
        <a href="<?= BASE_URL ?>/reports.php" class="btn btn-outline-secondary w-100 mb-2">
          Reports / Export
        </a>

      </div>
    </div>
  </div>

</div>

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