<?php
require_once APP_PATH . '/Core/BaseModel.php';

class Notification extends BaseModel {
    protected string $table = 'notifications';

    public function send(int $userId, string $type, string $title, string $body, string $url = ''): int {
        $this->execute(
            "INSERT INTO notifications (user_id, type, title, body, url) VALUES (?, ?, ?, ?, ?)",
            [$userId, $type, $title, $body, $url]
        );
        return (int) $this->db->lastInsertId();
    }

    public function getForUser(int $userId, int $limit = 20): array {
        return $this->fetchAll(
            "SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT ?",
            [$userId, $limit]
        );
    }

    public function markRead(int $id, int $userId): void {
        $this->execute(
            "UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ?",
            [$id, $userId]
        );
    }

    public function markAllRead(int $userId): void {
        $this->execute("UPDATE notifications SET is_read = 1 WHERE user_id = ?", [$userId]);
    }

    public function unreadCount(int $userId): int {
        return (int) $this->fetchOne(
            "SELECT COUNT(*) AS cnt FROM notifications WHERE user_id = ? AND is_read = 0",
            [$userId]
        )['cnt'];
    }
}
