<?php
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/mj_v3_helpers.php';
require_once __DIR__.'/../includes/mj_v30429_helpers.php';
header('Content-Type: application/json');
try { mj_v300_ensure_schema(); if(function_exists('mj429_ensure_schema')){mj429_ensure_schema();} $uid=(int)($_SESSION['user_id']??0); $aid=(int)($_SESSION['admin_id']??0); if(!$uid&&!$aid&&empty($_COOKIE['mj_customer_token'])){ setcookie('mj_customer_token',bin2hex(random_bytes(16)),time()+86400*365,'/'); }
$since=max(0,(int)($_GET['since']??0)); $items=[]; $unread=0; $latest=$since;
if(table_exists('mj_notifications')){ if($uid>0){ $unread=safe_count('SELECT COUNT(*) c FROM mj_notifications WHERE user_id=? AND is_read=0',[$uid]); $items=all_rows('SELECT id,title,message,action_url,priority,created_at,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 id>? ORDER BY id DESC LIMIT 5',[$uid,$since]); } elseif($aid>0){ $unread=safe_count('SELECT COUNT(*) c FROM mj_notifications WHERE admin_id=? AND is_read=0',[$aid]); $items=all_rows('SELECT id,title,message,action_url,priority,created_at,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 id>? ORDER BY id DESC LIMIT 5',[$aid,$since]); } foreach($items as $it){ $latest=max($latest,(int)$it['id']); } }
echo json_encode(['ok'=>true,'unread'=>$unread,'items'=>array_reverse($items),'latest_id'=>$latest]); } catch(Throwable $e){ echo json_encode(['ok'=>false,'error'=>'notification_error']); }
