<?php
// Filename: notifications_api.php
require 'config.php';
requireLogin();

header('Content-Type: application/json; charset=utf-8');

$user_id = (int)($_SESSION['user_id'] ?? 0);
if ($user_id <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Invalid session']);
    exit;
}

$mode  = (string)($_GET['mode'] ?? 'badge');
$limit = (int)($_GET['limit'] ?? 10);
if ($limit < 1) $limit = 10;
if ($limit > 50) $limit = 50;

function json_fail($msg, $code = 500) {
    http_response_code($code);
    echo json_encode(['ok' => false, 'error' => $msg]);
    exit;
}

try {
    // unread count
    if ($mode === 'badge') {
        $st = $GLOBALS['pdo']->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0");
        $st->execute([$GLOBALS['user_id'] ?? null]); // fallback not used
    }
} catch (Throwable $e) {
    // ignore - we will not use this broken block
}

/**
 * We do NOT rely on $GLOBALS tricks; do it cleanly
 */
try {
    if ($mode === 'badge') {
        $st = $pdo->prepare("SELECT COUNT(*) AS c FROM notifications WHERE user_id = ? AND is_read = 0");
        $st->execute([$user_id]);
        $count = (int)($st->fetchColumn() ?? 0);

        echo json_encode(['ok' => true, 'unread' => $count]);
        exit;
    }

    if ($mode === 'full') {
        // IMPORTANT: no "title" column here.
        // We expose a "title" field anyway for compatibility by mapping it to message.
        $st = $pdo->prepare("
            SELECT id,
                   message,
                   message AS title,
                   link,
                   created_at,
                   is_read
            FROM notifications
            WHERE user_id = ?
            ORDER BY id DESC
            LIMIT $limit
        ");
        $st->execute([$user_id]);
        $items = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

        echo json_encode(['ok' => true, 'items' => $items]);
        exit;
    }

    json_fail('Invalid mode', 400);

} catch (PDOException $e) {
    json_fail('DB error: ' . $e->getMessage(), 500);
} catch (Throwable $e) {
    json_fail('Server error: ' . $e->getMessage(), 500);
}
