<?php

declare(strict_types=1);
namespace App\Repositories;
use App\Core\Database;

final class NotificationRepository
{
    public function latest(int $userId, int $limit = 30): array
    {
        $stmt = Database::connection()->prepare('SELECT id,title,message,link,type,read_at,created_at FROM notifications WHERE user_id=:user_id ORDER BY created_at DESC,id DESC LIMIT :limit');
        $stmt->bindValue(':user_id',$userId,\PDO::PARAM_INT); $stmt->bindValue(':limit',$limit,\PDO::PARAM_INT); $stmt->execute(); return $stmt->fetchAll();
    }
    public function unreadCount(int $userId): int
    { $stmt=Database::connection()->prepare('SELECT COUNT(*) FROM notifications WHERE user_id=:user_id AND read_at IS NULL'); $stmt->execute(['user_id'=>$userId]); return (int)$stmt->fetchColumn(); }
    public function create(int $userId,string $title,string $message,?string $link=null,string $type='info'): int
    { $stmt=Database::connection()->prepare('INSERT INTO notifications(user_id,title,message,link,type) VALUES(:user_id,:title,:message,:link,:type)'); $stmt->execute(['user_id'=>$userId,'title'=>$title,'message'=>$message,'link'=>$link,'type'=>$type]); return (int)Database::connection()->lastInsertId(); }
    public function markRead(int $id,int $userId): void
    { Database::connection()->prepare('UPDATE notifications SET read_at=COALESCE(read_at,NOW()) WHERE id=:id AND user_id=:user_id')->execute(['id'=>$id,'user_id'=>$userId]); }
    public function markAllRead(int $userId): void
    { Database::connection()->prepare('UPDATE notifications SET read_at=NOW() WHERE user_id=:user_id AND read_at IS NULL')->execute(['user_id'=>$userId]); }
}
