Files
CRM-IKZ/app/Services/NotificationService.php
T
2026-07-14 08:19:56 +04:00

93 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use App\Core\DB;
class NotificationService
{
public function createForUsers(array $userIds, string $type, string $title, ?string $message = null, ?array $payload = null): void
{
$userIds = array_values(array_unique(array_map('intval', $userIds)));
$userIds = array_filter($userIds, fn($id) => $id > 0);
if (empty($userIds)) {
return;
}
$pdo = DB::connection();
$stmt = $pdo->prepare("
INSERT INTO notifications (
user_id,
type,
title,
message,
payload_json,
is_read,
created_at
) VALUES (?, ?, ?, ?, ?, 0, NOW())
");
$payloadJson = $payload ? json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : null;
foreach ($userIds as $userId) {
$stmt->execute([
$userId,
$type,
$title,
$message,
$payloadJson,
]);
}
}
public function getUnreadCount(int $userId): int
{
$pdo = DB::connection();
$stmt = $pdo->prepare("
SELECT COUNT(*)
FROM notifications
WHERE user_id = ?
AND is_read = 0
");
$stmt->execute([$userId]);
return (int)$stmt->fetchColumn();
}
public function getLatest(int $userId, int $limit = 20): array
{
$pdo = DB::connection();
$stmt = $pdo->prepare("
SELECT *
FROM notifications
WHERE user_id = ?
ORDER BY id DESC
LIMIT ?
");
$stmt->bindValue(1, $userId, \PDO::PARAM_INT);
$stmt->bindValue(2, $limit, \PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
public function markAllRead(int $userId): void
{
$pdo = DB::connection();
$stmt = $pdo->prepare("
UPDATE notifications
SET is_read = 1,
read_at = NOW()
WHERE user_id = ?
AND is_read = 0
");
$stmt->execute([$userId]);
}
}