<?php
require_once __DIR__ . '/db.php';

if (!function_exists('notify_user')) {
    function notify_user(PDO $pdo, int $userId, string $title, string $body = '', ?string $refType = null, ?int $refId = null, ?string $url = null): void {
        try {
            $st = $pdo->prepare("INSERT INTO notifications (user_id, title, body, ref_type, ref_id, url, is_read, created_at)
                                 VALUES (?,?,?,?,?,?,0,NOW())");
            $st->execute([$userId, $title, $body ?: null, $refType, $refId, $url]);
        } catch (Throwable $e) {
        }
    }
}

if (!function_exists('notify_role')) {
    /** Notify all active users with a role */
    function notify_role(PDO $pdo, string $role, string $title, string $body = '', ?string $refType = null, ?int $refId = null, ?string $url = null): void {
        $st = $pdo->prepare("SELECT id FROM users WHERE role=? AND is_active=1");
        $st->execute([$role]);
        foreach ($st->fetchAll(PDO::FETCH_COLUMN) as $uid) {
            notify_user($pdo, (int)$uid, $title, $body, $refType, $refId, $url);
        }
    }
}

if (!function_exists('fetch_unread_notifications')) {
    function fetch_unread_notifications(PDO $pdo, int $userId, int $limit = 8): array {
        $st = $pdo->prepare("SELECT * FROM notifications WHERE user_id=? AND is_read=0 ORDER BY id DESC LIMIT ?");
        $st->bindValue(1, $userId, PDO::PARAM_INT);
        $st->bindValue(2, $limit, PDO::PARAM_INT);
        $st->execute();
        return $st->fetchAll();
    }
}

if (!function_exists('mark_notification_read')) {
    function mark_notification_read(PDO $pdo, int $notifId, int $userId): void {
        $pdo->prepare("UPDATE notifications SET is_read=1 WHERE id=? AND user_id=?")->execute([$notifId, $userId]);
    }
}
