<?php
/* ============================================================================
 *  notif_badge.php — app-icon badge count for the logged-in user.
 *    action 'count' → returns unread notification count
 *    action 'seen'  → marks all read, returns 0 (call when the app is opened)
 * ==========================================================================*/
session_start();
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/config/database.php';

if (!isset($_SESSION['user_id'])) { echo json_encode(['count'=>0]); exit; }
$userId = (int)$_SESSION['user_id'];
$in = json_decode(file_get_contents('php://input'), true) ?: [];
$action = $in['action'] ?? 'count';

try {
    if ($action === 'seen') {
        $pdo->prepare("UPDATE notifications SET is_read=1 WHERE user_id=? AND is_read=0")->execute([$userId]);
        echo json_encode(['count'=>0]); exit;
    }
    $c = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND is_read=0");
    $c->execute([$userId]);
    echo json_encode(['count'=>(int)$c->fetchColumn()]);
} catch (Throwable $e) { echo json_encode(['count'=>0]); }