<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/middleware/auth.php';
require_once __DIR__ . '/../app/models/Notification.php';

require_login();
$user = current_user();

// OPTIONAL: Only admins should view notifications page
// If you want staff to also view, comment this out.
if (($user['role'] ?? '') !== 'admin') {
  http_response_code(403);
  exit('Forbidden');
}

$filter = strtolower(trim($_GET['filter'] ?? 'unread')); // unread | all
if (!in_array($filter, ['unread', 'all'], true)) $filter = 'unread';

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

$rows = ($filter === 'all')
  ? Notification::listByUser((int)$user['id'], 200, false)
  : Notification::listByUser((int)$user['id'], 200, true);

$unreadCount = Notification::unreadCount((int)$user['id']);

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">Notifications</h5>
        <div class="text-muted small">
          Unread: <strong><?= (int)$unreadCount ?></strong>
        </div>
      </div>

      <div class="d-flex gap-2 flex-wrap">
        <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/dashboard.php">Back to Dashboard</a>

        <a class="btn btn-outline-primary <?= $filter === 'unread' ? 'active' : '' ?>"
           href="<?= BASE_URL ?>/notifications.php?filter=unread">
          Unread
        </a>
        <a class="btn btn-outline-primary <?= $filter === 'all' ? 'active' : '' ?>"
           href="<?= BASE_URL ?>/notifications.php?filter=all">
          All
        </a>

        <?php if ($unreadCount > 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-outline-secondary">Mark all as read</button>
          </form>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="card p-4">
    <?php if (!$rows): ?>
      <div class="text-muted">No notifications found.</div>
    <?php else: ?>
      <div class="list-group">
        <?php foreach ($rows as $n): ?>
          <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((string)($n['type'] ?? '')) ?>
                  <div class="fw-semibold"><?= htmlspecialchars($n['title'] ?? '') ?></div>

                  <?php if ((int)($n['is_read'] ?? 0) === 0): ?>
                    <span class="badge text-bg-danger">UNREAD</span>
                  <?php endif; ?>
                </div>

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

                <div class="small text-muted mt-2">
                  <?= htmlspecialchars($n['created_at'] ?? '') ?>
                  <?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; ?>

                  <?php if ((int)($n['is_read'] ?? 0) === 0): ?>
                    <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>
                  <?php endif; ?>
                </div>
              </div>

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

</div>

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