<?php
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/mj_v30429_helpers.php';
header('Content-Type: application/json');
try{
  mj263_schema(); if(function_exists('mj429_ensure_schema')){mj429_ensure_schema();} $uid=(int)($_SESSION['user_id']??0); $aid=(int)($_SESSION['admin_id']??0); $items=[]; $unread=0;
  if(table_exists('mj_notifications') && ($uid || $aid)){
    if($uid){ $unread=safe_count('SELECT COUNT(*) c FROM mj_notifications WHERE user_id=? AND is_read=0 AND (is_archived IS NULL OR is_archived=0)',[$uid]); $items=all_rows('SELECT id,title,message,action_url,priority,notification_key,dedupe_hash,type,lead_id FROM mj_notifications WHERE user_id=? AND is_read=0 AND (is_archived IS NULL OR is_archived=0) AND is_popup_shown=0 ORDER BY FIELD(priority,"critical","urgent","high","normal","low"), id DESC LIMIT 3',[$uid]); }
    elseif($aid){ $unread=safe_count('SELECT COUNT(*) c FROM mj_notifications WHERE admin_id=? AND is_read=0 AND (is_archived IS NULL OR is_archived=0)',[$aid]); $items=all_rows('SELECT id,title,message,action_url,priority,notification_key,dedupe_hash,type,lead_id FROM mj_notifications WHERE admin_id=? AND is_read=0 AND (is_archived IS NULL OR is_archived=0) AND is_popup_shown=0 ORDER BY FIELD(priority,"critical","urgent","high","normal","low"), id DESC LIMIT 3',[$aid]); }
    foreach($items as $it){ q('UPDATE mj_notifications SET is_popup_shown=1,popup_shown_at=NOW() WHERE id=?',[(int)$it['id']]); }
  }
  echo json_encode(['ok'=>true,'unread'=>$unread,'items'=>$items]);
}catch(Throwable $e){ echo json_encode(['ok'=>false]); }
