<?php
session_start();
require_once __DIR__ . '/../includes/db.php';

// ✅ Redirect to login if user not logged in
if (empty($_SESSION['user_id'])) {
    header("Location: /login");
    exit;
}

$user_id = $_SESSION['user_id'];

// ✅ Fetch unread count
$stmt = $pdo->prepare("SELECT COUNT(*) AS unread FROM notifications WHERE user_id = ? AND is_read = 0");
$stmt->execute([$user_id]);
$unread = $stmt->fetch(PDO::FETCH_ASSOC)['unread'];

// ✅ Fetch all notifications (Newest First)
$stmt = $pdo->prepare("SELECT id, title, message, is_read, created_at FROM notifications WHERE user_id = ? ORDER BY id DESC");
$stmt->execute([$user_id]);
$notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ✅ Mark all as read when page opens
$pdo->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ?")->execute([$user_id]);
?>

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Notifications - BmellonIntl</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

<style>
:root {
  --bg-color: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
  --card-bg: rgba(255, 255, 255, 0.08);
  --text-color: #fff;
}
body.light-mode {
  --bg-color: #f5f6fa;
  --card-bg: #fff;
  --text-color: #222;
}
body {
  background: var(--bg-color);
  color: var(--text-color);
  min-height: 100vh;
  font-family: 'Poppins', sans-serif;
}
.card {
  background: var(--card-bg);
  border-radius: 1rem;
  border: none;
  padding: 1rem;
}
.notification-item {
  padding: 1rem;
  border-bottom: 1px solid rgba(255,255,255,0.08);
  transition: background .3s ease;
}
.notification-item.unread {
  background: rgba(0,180,216,0.15);
}
.notification-item:hover {
  background: rgba(255,255,255,0.06);
}
.text-gradient {
  background: linear-gradient(90deg, #00b4d8, #48cae4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
</style>
</head>

<body>

<!-- Navbar -->
<nav class="navbar navbar-dark px-3" style="background:rgba(0,0,0,0.6);backdrop-filter:blur(12px);">
    <a class="navbar-brand" href="/dashboard">BmellonIntl</a>
    <span class="ms-auto text-light fw-semibold">Notifications</span>
</nav>

<div class="container py-4">
  <div class="card">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="text-gradient mb-0">Notifications</h4>
      <?php if($unread > 0): ?>
        <span class="badge bg-danger"><?php echo $unread; ?> New</span>
      <?php endif; ?>
    </div>

    <?php if(count($notifications) == 0): ?>
      <p class="text-center text-muted py-5">No notifications yet.</p>
    <?php endif; ?>

    <?php foreach ($notifications as $note): ?>
      <div class="notification-item <?php echo $note['is_read'] ? '' : 'unread'; ?>">
        <h6 class="fw-bold mb-1"><?php echo htmlspecialchars($note['title']); ?></h6>
        <p class="mb-1"><?php echo htmlspecialchars($note['message']); ?></p>
        <small class="text-secondary">
            <i class="bi bi-clock"></i>
            <?php echo date("M j, Y - g:i A", strtotime($note['created_at'])); ?>
        </small>
      </div>
    <?php endforeach; ?>
  </div>
</div>

<!-- Theme Toggle -->
<div class="theme-toggle bi bi-brightness-high" style="
  position: fixed; right:20px; top:50%; transform:translateY(-50%);
  background:#00b4d8; color:white; width:48px; height:48px;
  border-radius:50%; display:flex; align-items:center; justify-content:center; cursor:pointer;">
</div>

<script>
// ✅ Fix theme toggle (event must be defined)
const themeToggle = document.querySelector('.theme-toggle');
themeToggle.addEventListener('click', (event) => {
  document.body.classList.toggle('light-mode');
  event.target.classList.toggle('bi-moon');
  event.target.classList.toggle('bi-brightness-high');
});

// // ✅ Allow audio playback after first user interaction
// document.addEventListener("click", () => {
//   const sound = document.getElementById("notifySound");
//   sound.volume = 1.0;
//   sound.play().catch(()=>{});
// }, { once: true });

// // ✅ Notification Auto-Refresh + Sound + Vibrate
// let lastCount = <?php echo (int)$unread; ?>;

// function refreshNotifications() {
//   fetch('/../actions/fetch_unread_count')
//     .then(res => res.json())
//     .then(data => {
//       let newCount = data.unread;

//       // ✅ If new notifications arrived → Play sound & vibrate
//       if (newCount > lastCount) {
//         const sound = document.getElementById('notifySound');
//         sound.currentTime = 0;
//         sound.play().catch(()=>{});
        
//         if (navigator.vibrate) navigator.vibrate([150, 70, 150]);
//       }

//       lastCount = newCount;
//     })
//     .catch(() => {});
// }

// // ✅ Refresh every 10 seconds
// setInterval(refreshNotifications, 10000);
</script>

<audio id="notifySound" preload="auto">
  <source src="../includes/sounds/ping.mp3" type="audio/mp3">
</audio>


</body>
</html>
