<?php
declare(strict_types=1);
require_once __DIR__ . '/../Config/database.php';

class NotificationsController
{
    private PDO $db;
    public function __construct() { $this->db = Database::getConnection(); }

    public function fetch(int $userId): array {
        $stmt = $this->db->prepare("SELECT id,title,message,is_read,created_at 
                                    FROM notifications 
                                    WHERE user_id IS NULL OR user_id=:uid 
                                    ORDER BY id DESC LIMIT 10");
        $stmt->execute(['uid'=>$userId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function markRead(int $userId): bool {
        $stmt = $this->db->prepare("UPDATE notifications 
                                    SET is_read=1 
                                    WHERE user_id IS NULL OR user_id=:uid");
        return $stmt->execute(['uid'=>$userId]);
    }

    public static function push(?int $userId, string $title, string $message): void {
        try {
            $db = Database::getConnection();
            $stmt = $db->prepare("INSERT INTO notifications (user_id,title,message,is_read,created_at)
                                  VALUES (:uid,:t,:m,0,NOW())");
            $stmt->execute(['uid'=>$userId,'t'=>$title,'m'=>$message]);
        } catch (Throwable $e) {
            // optional logging
        }
    }
}
