<?php
declare(strict_types=1);
require_once __DIR__ . '/../../Config/config.php';
require_once __DIR__ . '/../../Config/functions.php';
require_once __DIR__ . '/../../Controllers/NotificationsController.php';
require_login();

$controller = new NotificationsController();
$userId = (int)($_SESSION['user_id'] ?? 0);

$filter = $_GET['filter'] ?? 'unread';
$pageNum = max(1, (int)($_GET['p'] ?? 1));
$perPage = 10;
$offset = ($pageNum - 1) * $perPage;

// Build query
$db = Database::getConnection();
$where = ($filter === 'unread') ? 'WHERE (user_id IS NULL OR user_id=:uid) AND is_read=0'
                                : 'WHERE (user_id IS NULL OR user_id=:uid)';
$stmt = $db->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM notifications 
                      $where ORDER BY created_at DESC LIMIT :o, :l");
$stmt->bindValue(':uid', $userId, PDO::PARAM_INT);
$stmt->bindValue(':o', $offset, PDO::PARAM_INT);
$stmt->bindValue(':l', $perPage, PDO::PARAM_INT);
$stmt->execute();
$notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
$total = (int)$db->query("SELECT FOUND_ROWS()")->fetchColumn();
$totalPages = (int)ceil($total / $perPage);

$title = 'Notifications';
$page = 'notifications';

include __DIR__ . '/../layouts/header.php';
include __DIR__ . '/../layouts/sidebar.php';
?>

<div class="content-wrapper">
  <section class="content-header d-flex justify-content-between align-items-center">
    <h1><i class="far fa-bell mr-2"></i> Notifications</h1>
    <div>
      <a href="router.php?page=notifications&filter=all" 
         class="btn btn-sm btn-outline-primary <?= $filter==='all'?'active':'' ?>">All</a>
      <a href="router.php?page=notifications&filter=unread" 
         class="btn btn-sm btn-outline-secondary <?= $filter==='unread'?'active':'' ?>">Unread</a>
      <button id="markAllRead" class="btn btn-sm btn-success ml-2">
        <i class="fas fa-check"></i> Mark All Read
      </button>
    </div>
  </section>

  <section class="content">
    <div class="card card-outline card-primary">
      <div class="card-body">
        <?php if (empty($notifications)): ?>
          <p class="text-center text-muted mb-0">No notifications found.</p>
        <?php else: ?>
        <div class="list-group">
          <?php foreach ($notifications as $n): ?>
            <div class="list-group-item d-flex justify-content-between align-items-start <?= $n['is_read']?'bg-light':'' ?>">
              <div>
                <h5 class="mb-1 <?= $n['is_read']?'text-muted':'' ?>">
                  <i class="fas fa-info-circle mr-2 text-primary"></i><?= e($n['title']) ?>
                </h5>
                <p class="mb-1 small <?= $n['is_read']?'text-muted':'' ?>">
                  <?= e($n['message']) ?>
                </p>
              </div>
              <small class="text-muted"><?= date('d M Y H:i', strtotime($n['created_at'])) ?></small>
            </div>
          <?php endforeach; ?>
        </div>

        <!-- Pagination -->
        <nav class="mt-3">
          <ul class="pagination justify-content-center">
            <?php for ($i=1; $i<=$totalPages; $i++): ?>
              <li class="page-item <?= $i==$pageNum?'active':'' ?>">
                <a class="page-link" href="router.php?page=notifications&filter=<?= $filter ?>&p=<?= $i ?>"><?= $i ?></a>
              </li>
            <?php endfor; ?>
          </ul>
        </nav>
        <?php endif; ?>
      </div>
    </div>
  </section>
</div>

<?php include __DIR__ . '/../layouts/footer.php'; ?>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$('#markAllRead').on('click', function(){
  $.get('app/Views/notifications/ajax/mark-read.php', res=>{
    Swal.fire('Done','All notifications marked as read','success')
        .then(()=>location.reload());
  });
});
</script>
