<?php
require_once 'Database.php';

class Notification {
    private $db;

    public function __construct() {
        $this->db = new Database();
    }

    public function create($user_id, $message, $link = null) {
        $stmt = $this->db->query(
            "INSERT INTO notifications (user_id, message, link) VALUES (?, ?, ?)",
            [$user_id, $message, $link]
        );
        return $this->db->lastInsertId();
    }

    public function getUnread($user_id) {
        $stmt = $this->db->query(
            "SELECT * FROM notifications WHERE user_id = ? AND is_read = FALSE ORDER BY created_at DESC",
            [$user_id]
        );
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function markAsRead($notification_ids, $user_id) {
        if (empty($notification_ids) || !is_array($notification_ids)) {
            return 0;
        }

        // Ensure all IDs are integers to prevent SQL injection
        $ids = array_map('intval', $notification_ids);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));

        $params = $ids;
        $params[] = $user_id;

        $stmt = $this->db->query(
            "UPDATE notifications SET is_read = TRUE WHERE id IN ($placeholders) AND user_id = ?",
            $params
        );

        return $stmt->rowCount();
    }
}
?>