<?php

require_once __DIR__ . '/config.php';

$role = $_SESSION['role'] ?? '';
$userId = (int)$_SESSION['user_id'];

if ($role === 'medical_representative') {

    $dueItems = $conn->query("
        SELECT customer_name, total_amount 
        FROM bills 
        WHERE payment_status='unpaid'
        AND mr_id = $userId
        LIMIT 2
    ");

} elseif ($role === 'sales_manager') {

    $dueItems = $conn->query("
        SELECT b.customer_name, b.total_amount
        FROM bills b
        JOIN users u ON u.id = b.mr_id
        WHERE b.payment_status='unpaid'
        AND u.manager_id = $userId
        LIMIT 2
    ");

} else {

    $dueItems = $conn->query("
        SELECT customer_name, total_amount 
        FROM bills 
        WHERE payment_status='unpaid'
        LIMIT 2
    ");
}

$profilePath = match ($role) {
    'admin' => '../Admin/profile.php',
    'agency' => '../agency/profile.php',
    'ra' => '../Ra/profile.php',
'sales_manager' => '../SalesManager/profile.php',
    'medical_representative' => '../medicalrepresentative/profile.php',
    default => '../profile.php',
};
$username = trim($_SESSION['name'] ?? 'User');

$panelName = match ($role) {
    'admin' => 'Admin',
    'agency' => 'Agency',
    'ra' => 'RA',
    'sales_manager' => 'Sales Manager',
    'medical_representative' => 'medicalrepresentative',
    default => 'User',
};

$initial = strtoupper(substr($_SESSION['name'] ?? 'A', 0, 1));

$user_id = (int)($_SESSION['user_id'] ?? 0);
$notificationCount = 0;
$notifications = [];

if ($user_id > 0) {
    // unread count
   $countStmt = $conn->prepare("
    SELECT COUNT(*) AS total
    FROM notifications
    WHERE (user_id = ? OR user_id IS NULL) AND is_read = 0
");
    $countStmt->bind_param("i", $user_id);
    $countStmt->execute();
    // existing notifications count
$dbCount = (int)($countStmt->get_result()->fetch_assoc()['total'] ?? 0);

// LOW STOCK
$lowRes = $conn->query("SELECT COUNT(*) as c FROM products WHERE qty <= 10");
$lowCount = (int)($lowRes->fetch_assoc()['c'] ?? 0);

// EXPIRY
$expRes = $conn->query("
    SELECT COUNT(*) as c FROM products 
    WHERE registration_exp_date IS NOT NULL 
    AND registration_exp_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)
");
$expCount = (int)($expRes->fetch_assoc()['c'] ?? 0);

// DUES
$dueRes = $conn->query("
    SELECT COUNT(*) as c FROM bills WHERE payment_status='unpaid'
");
$dueCount = (int)($dueRes->fetch_assoc()['c'] ?? 0);

// FINAL COUNT
$notificationCount = $dbCount + $lowCount + $expCount + $dueCount;

    // latest 5 alerts
 $listStmt = $conn->prepare("
    SELECT id, message, created_at, is_read
    FROM notifications
    WHERE (user_id = ? OR user_id IS NULL)
    ORDER BY created_at DESC
    LIMIT 5
");
    $listStmt->bind_param("i", $user_id);
    $listStmt->execute();
    $notifications = $listStmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

$notificationsUrl = '../notifications.php';
?>
<!-- adminheader.php -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
:root{
  --bg-1:#ffffff;
  --bg-2:#ffffff;
  --text-on-dark:#111827;
  --muted:#6b7280;
  --accent:#2563eb;
  --header-height: 65px;
  --muted: #9aa6bf;
  --accent: #3b82f6;
}

/* header */
.header{
  position:fixed;
  top:0;
  left:260px;
  right:0;
  height:var(--header-height);
  background:#ffffff;  display:flex;
  align-items:center;
  justify-content:space-between;
  padding:0 20px;
  color:#111827;
  box-shadow:0 2px 12px rgba(0,0,0,0.08);
  border-bottom:1px solid #e5e7eb;  z-index:900;
  gap:12px;
  transition:left .22s ease;
  font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial;
}

/* when sidebar collapsed */
.sidebar.collapsed ~ .header{ left:76px; }

/* left area */
.header-left{ display:flex; align-items:center; gap:18px; }
.page-title{
  font-weight:700;
  font-size:18px;
  color:var(--text-on-dark);
  letter-spacing:0.2px;
}

/* optional small subtitle */
.page-sub {
  font-size:13px; color:var(--muted);
}

/* right area */
.header-right{ display:flex; align-items:center; gap:14px; }

/* ------------- notification ------------- */
.notification{
  position:relative;
  width:42px;
  height:42px;
  display:flex;
  align-items:center;
  justify-content:center;
  cursor:pointer;
  border-radius:12px;
  background:#f8fafc;
  border:1px solid #e5e7eb;
  transition:all 0.25s ease;
}

/* hover effect */
.notification:hover{
  background:#eef2ff;
  border-color:#c7d2fe;
}

/* bell icon */
.notification i{
  font-size:16px;
  color:#374151;
}

/* bell icon - ensure visible on dark bg */
.notification .fa-bell{ color: #111827; font-size:18px; }

/* badge */
.notification-badge{
  position:absolute;
  top:-4px;
  right:-4px;
  min-width:18px;
  height:18px;
  padding:0 5px;
  display:flex;
  align-items:center;
  justify-content:center;
  background:#ef4444;
  color:#fff;
  font-size:10px;
  font-weight:700;
  border-radius:999px;
  border:2px solid #fff;
}
.notification{
  box-shadow:0 2px 6px rgba(0,0,0,0.05);
}
@keyframes notif-pulse{
  0%{ transform: scale(1); }
  50%{ transform: scale(1.15); }
  100%{ transform: scale(1); }
}

/* dropdown */
.notification-menu{
  position:absolute;
  top: calc(var(--header-height) + 8px);
  right:0;
  width:320px;
  max-height:420px;
  background:#fff;
  color:#111827;
  border-radius:12px;
  box-shadow:0 12px 40px rgba(2,6,23,0.35);
  display:none;
  flex-direction:column;
  overflow:hidden;
  z-index:10000;
}

/* show */
.notification-menu.show{ display:flex; }

/* header inside dropdown */
.notify-header{
  padding:12px 14px; font-weight:700; border-bottom:1px solid #f1f5f9;
  display:flex; align-items:center; justify-content:space-between;
}

/* list */
.notify-list{ overflow:auto; max-height:300px; }

/* item */
.notify-item{
  display:flex; gap:12px; padding:12px 14px; align-items:flex-start;
  border-bottom:1px solid #f8fafc; cursor:pointer;
}
.notify-item:hover{ background:#fbfdff; }
.notify-item i{ font-size:18px; color:var(--accent); margin-top:4px; }
.notify-item strong{ display:block; font-size:13px; }
.notify-item p{ margin:2px 0 0; font-size:13px; color:#64748b; }

/* footer */
.notify-footer{ padding:10px; text-align:center; border-top:1px solid #f1f5f9; }
.notify-footer a{ text-decoration:none; color:var(--accent); font-weight:600; }

/* ------------- profile ------------- */
.profile{
  position:relative;
  display:flex;
  align-items:center;
  gap:10px;
  cursor:pointer;
}
.user-avatar{
  width:40px; height:40px; border-radius:10px;
  display:inline-grid; place-items:center;
  background:#fff; color:var(--bg-1); font-weight:700; font-size:15px;
  box-shadow: 0 6px 18px rgba(2,6,23,0.25);
}
.profile-name{
  display:flex; align-items:center; gap:8px;color:#111827; font-weight:600; font-size:14px;
}

/* profile dropdown */
.profile-menu{
  position:absolute;
  top: calc(var(--header-height) + 8px);
  right:0;
  background:#fff; border-radius:10px; box-shadow:0 12px 40px rgba(2,6,23,0.25);
  width:200px; display:none; flex-direction:column; overflow:hidden; z-index:10000;
}
.profile-menu.show{ display:flex; }
.profile-menu a{ padding:12px 14px; text-decoration:none; color:#0f1724; font-size:14px; }
.profile-menu a:hover{ background:#f8fafc; }
.user-avatar{
  background:#f1f5f9;
  color:#111827;
  box-shadow:none;
}
/* responsive */
@media (max-width:920px){
  .header{ padding:0 14px; }
  .page-title{ font-size:16px; }
  .notification-menu{ right:6px; left:auto; width:300px; }
  .profile-menu{ right:6px; }
  .header{ left:0; } /* allow header take full width on very small screens; sidebar should be toggled */
}

/* ensure content below header does not hide under it (recommended class) */
.main-content{ margin-top: calc(var(--header-height) + 18px); transition: margin-left .22s ease; }
.sidebar.collapsed ~ .main-content{ margin-left:76px; }
</style>

<header class="header" role="banner" aria-label="Top header">
  <div class="header-left">
    <div class="page-title"></div>
  </div>

  <div class="header-right" role="navigation" aria-label="Header controls">

    <!-- notification -->
    <div class="notification" id="notificationBtn" aria-haspopup="true" aria-expanded="false" title="Notifications">
    <i class="fa-solid fa-bell" aria-hidden="true"></i>
    <span class="notification-badge" id="notificationCount"><?php echo $notificationCount; ?></span>

    <div class="notification-menu" id="notificationMenu" role="menu" aria-label="Notifications list">
        <div class="notify-header">
            <span>Notifications</span>
            <small style="color:var(--muted);font-weight:600" id="notifTime">Now</small>
        </div>

       <?php
// LOW STOCK
$lowItems = $conn->query("SELECT product_name, qty FROM products WHERE qty <= 10 LIMIT 2");
while ($l = $lowItems->fetch_assoc()):
?>
<div class="notify-item">
    <i class="fa-solid fa-box" style="color:red;"></i>
    <div>
        <strong>Low Stock</strong>
        <p><?php echo $l['product_name']; ?> (Qty: <?php echo $l['qty']; ?>)</p>
    </div>
</div>
<?php endwhile; ?>

<?php
// EXPIRY
$expItems = $conn->query("
    SELECT product_name, registration_exp_date 
    FROM products 
    WHERE registration_exp_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)
    LIMIT 2
");
while ($e = $expItems->fetch_assoc()):
?>
<div class="notify-item">
    <i class="fa-solid fa-clock" style="color:orange;"></i>
    <div>
        <strong>Expiry Alert</strong>
        <p><?php echo $e['product_name']; ?> (<?php echo date('d M', strtotime($e['registration_exp_date'])); ?>)</p>
    </div>
</div>
<?php endwhile; ?>

<?php

while ($d = $dueItems->fetch_assoc()):
?>
<div class="notify-item">
    <i class="fa-solid fa-indian-rupee-sign" style="color:blue;"></i>
    <div>
        <strong>Unpaid Due</strong>
        <p><?php echo $d['customer_name']; ?> (₹<?php echo $d['total_amount']; ?>)</p>
    </div>
</div>
<?php endwhile; ?>

<!-- OLD NOTIFICATIONS -->
<?php foreach ($notifications as $row): ?>
<a href="<?php echo $notificationsUrl; ?>?read=<?php echo (int)$row['id']; ?>" class="notify-item">
    <i class="fa-solid fa-bell"></i>
    <div>
        <strong>Alert</strong>
        <p><?php echo htmlspecialchars($row['message']); ?></p>
    </div>
</a>
<?php endforeach; ?>

        <div class="notify-footer">
            <a href="<?php echo $notificationsUrl; ?>">View All</a>
        </div>
    </div>
</div>

<div class="profile" id="profileBtn" aria-haspopup="true" aria-expanded="false" title="Account">
    <div class="user-avatar" id="userAvatar"><?php echo htmlspecialchars($initial); ?></div>
    <div class="profile-name"><?php echo htmlspecialchars($panelName); ?></div>

      <div class="profile-menu" id="profileMenu" role="menu" aria-label="Account menu">
        <a href="<?php echo $profilePath; ?>"><i class="fa-solid fa-user" style="width:18px;"></i> &nbsp; My Profile</a>
        <a href="../logout.php" style="color:#ef4444"><i class="fa-solid fa-right-from-bracket" style="width:18px;"></i> &nbsp; Logout</a>
      </div>
    </div>

  </div>
</header>

<script>
(function(){
  // elements
  const notificationBtn = document.getElementById('notificationBtn');
  const notificationMenu = document.getElementById('notificationMenu');
  const profileBtn = document.getElementById('profileBtn');
  const profileMenu = document.getElementById('profileMenu');

  // toggle helper
  function toggleMenu(button, menu) {
    if(!button || !menu) return;
    const isOpen = menu.classList.toggle('show');
    button.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
  }

  // close all
  function closeAll() {
    if(notificationMenu) { notificationMenu.classList.remove('show'); notificationBtn && notificationBtn.setAttribute('aria-expanded','false'); }
    if(profileMenu) { profileMenu.classList.remove('show'); profileBtn && profileBtn.setAttribute('aria-expanded','false'); }
  }

  // click handlers
  notificationBtn && notificationBtn.addEventListener('click', function(e){
    e.stopPropagation();
    toggleMenu(notificationBtn, notificationMenu);
    // close profile if open
    if(profileMenu && profileMenu.classList.contains('show')) profileMenu.classList.remove('show');
  });

  profileBtn && profileBtn.addEventListener('click', function(e){
    e.stopPropagation();
    toggleMenu(profileBtn, profileMenu);
    // close notification if open
    if(notificationMenu && notificationMenu.classList.contains('show')) notificationMenu.classList.remove('show');
  });

  // keyboard accessibility for toggles (Enter / Space)
  [notificationBtn, profileBtn].forEach(btn=>{
    if(!btn) return;
    btn.addEventListener('keydown', (e)=>{
      if(e.key === 'Enter' || e.key === ' ') { e.preventDefault(); btn.click(); }
    });
  });

  // close on outside click or Escape
  document.addEventListener('click', closeAll);
  document.addEventListener('keydown', function(e){ if(e.key === 'Escape') closeAll(); });

  // stop propagation inside menus so clicks don't bubble to document
  [notificationMenu, profileMenu].forEach(menu => { if(menu) menu.addEventListener('click', e => e.stopPropagation()); });

  // Optional: demo dynamic count (replace with AJAX from server)
  // const notificationCountEl = document.getElementById('notificationCount');
  // notificationCountEl.textContent = '3';

})();
</script>