<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/mj_v3041_access_notifications_location.php';
require_once __DIR__ . '/../includes/mj_v30429_helpers.php';
header('Content-Type: application/json; charset=utf-8');
function mjv3041_njson(array $data): void { echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; }
try {
    mjv3041_ensure_light_schema(); if (function_exists('mj429_ensure_schema')) { mj429_ensure_schema(); }
    // v3.0.4.2.17: archive duplicate notifications occasionally so badges and popups stay clean.
    try { if (function_exists('mj429_archive_duplicate_notifications')) { $last=(int)($_SESSION['mj429_dedupe_at'] ?? 0); if ($last < time()-300) { mj429_archive_duplicate_notifications(); $_SESSION['mj429_dedupe_at']=time(); } } } catch (Throwable $ignore) {}
    $uid = (int)($_SESSION['user_id'] ?? 0); $aid = (int)($_SESSION['admin_id'] ?? 0);
    $isAdmin = $aid > 0; $action = strtolower((string)($_POST['action'] ?? $_GET['action'] ?? 'list'));
    if (!$uid && !$aid) { mjv3041_njson(['ok'=>true,'unread'=>0,'items'=>[],'badges'=>[]]); }
    $cols = mjv3041_columns('mj_notifications');
    if ($action === 'read') {
        $id=(int)($_POST['id']??0); if($id>0){ q('UPDATE mj_notifications SET is_read=1, read_at=NOW() WHERE id=?',[$id]); }
    } elseif ($action === 'read_all') {
        if ($isAdmin) {
            if (in_array('user_type',$cols,true)) { q("UPDATE mj_notifications SET is_read=1, read_at=NOW() WHERE is_read=0 AND (user_type='admin' OR admin_id IS NOT NULL)"); }
            else { q('UPDATE mj_notifications SET is_read=1, read_at=NOW() WHERE is_read=0 AND admin_id IS NOT NULL'); }
        } else { q('UPDATE mj_notifications SET is_read=1, read_at=NOW() WHERE is_read=0 AND user_id=?',[$uid]); }
    }
    $where=[]; $params=[];
    if ($isAdmin) {
        if (in_array('user_type',$cols,true) && in_array('admin_id',$cols,true)) { $where[]="(user_type='admin' OR admin_id=? OR admin_id IS NULL)"; $params[]=$aid; }
        elseif (in_array('admin_id',$cols,true)) { $where[]='(admin_id=? OR admin_id IS NULL)'; $params[]=$aid; }
        else { $where[]='1=0'; }
    } else { $where[]='user_id=?'; $params[]=$uid; if (in_array('user_type',$cols,true)) { $where[]="(user_type IS NULL OR user_type='' OR user_type='user')"; } }
    $where[] = "(is_archived IS NULL OR is_archived=0)";
    $whereSql = $where ? implode(' AND ', $where) : '1=1';
    $unread = 0; $items=[];
    if (mjv3041_table_exists('mj_notifications')) {
        $unread = (int)(one('SELECT COUNT(*) c FROM mj_notifications WHERE is_read=0 AND '.$whereSql, $params)['c'] ?? 0);
        $rows = all_rows('SELECT * FROM mj_notifications WHERE '.$whereSql.' ORDER BY created_at DESC, id DESC LIMIT 40', $params);
        if (function_exists('mj429_dedupe_notification_rows')) { $rows = mj429_dedupe_notification_rows($rows); }
        $rows = array_slice($rows, 0, 20);
        foreach($rows as $r){ $items[]=['id'=>(int)($r['id']??0),'title'=>(string)($r['title']??'Notification'),'message'=>(string)($r['message']??$r['body']??''),'type'=>(string)($r['type']??$r['priority']??'info'),'link'=>(string)($r['link']??$r['action_url']??$r['url']??''),'is_read'=>(int)($r['is_read']??0),'created_at'=>(string)($r['created_at']??''),'notification_key'=>(string)($r['notification_key']??$r['_dedupe_key']??''),'dedupe_key'=>(string)($r['_dedupe_key']??$r['notification_key']??'')]; }
    }
    $badges = ['notifications'=>$unread,'leads'=>0,'chat'=>0];
    try {
        if (mjv3041_table_exists('seller_leads')) { $badges['leads'] = $isAdmin ? (int)(one("SELECT COUNT(*) c FROM seller_leads WHERE status='new'")['c']??0) : (int)(one("SELECT COUNT(*) c FROM seller_leads WHERE seller_user_id=? AND (status='new' OR is_read=0)",[$uid])['c']??0); }
    } catch(Throwable $e) {}
    try {
        if (!$isAdmin && mjv3041_table_exists('mj_chat_messages') && mjv3041_table_exists('mj_chats')) { $badges['chat'] = (int)(one('SELECT COUNT(*) c FROM mj_chat_messages m INNER JOIN mj_chats c ON c.id=m.chat_id WHERE m.is_read=0 AND m.sender_id<>? AND (c.buyer_id=? OR c.seller_id=?)',[$uid,$uid,$uid])['c']??0); }
    } catch(Throwable $e) {}
    mjv3041_njson(['ok'=>true,'unread'=>$unread,'items'=>$items,'badges'=>$badges]);
} catch (Throwable $e) { mjv3041_njson(['ok'=>false,'error'=>$e->getMessage(),'unread'=>0,'items'=>[],'badges'=>[]]); }
