<?php
declare(strict_types=1);

namespace App\Models;

final class Notification extends BaseModel
{
    protected static string $table = 'notifications';
    protected static bool $softDelete = false;

    public static function unread(int $userId, int $limit = 8): array
    {
        return static::db()->fetchAll(
            'SELECT * FROM notifications WHERE tenant_id = :tid AND user_id = :uid AND is_read = 0 ORDER BY created_at DESC LIMIT ' . $limit,
            ['tid' => static::tenantId(), 'uid' => $userId]
        );
    }

    public static function unreadCount(int $userId): int
    {
        return (int) static::db()->fetchColumn(
            'SELECT COUNT(*) FROM notifications WHERE tenant_id = :tid AND user_id = :uid AND is_read = 0',
            ['tid' => static::tenantId(), 'uid' => $userId]
        );
    }

    public static function findOwned(int $id, int $userId): ?array
    {
        return static::db()->fetch(
            'SELECT * FROM notifications WHERE id = :id AND user_id = :uid AND tenant_id = :tid',
            ['id' => $id, 'uid' => $userId, 'tid' => static::tenantId()]
        );
    }

    public static function markRead(int $id, int $userId): void
    {
        static::db()->query(
            'UPDATE notifications SET is_read = 1 WHERE id = :id AND user_id = :uid AND tenant_id = :tid',
            ['id' => $id, 'uid' => $userId, 'tid' => static::tenantId()]
        );
    }

    public static function existsToday(int $userId, string $title, string $url, ?string $body = null): bool
    {
        $sql = 'SELECT COUNT(*) FROM notifications
                WHERE tenant_id = :tid AND user_id = :uid AND title = :title AND url = :url
                  AND DATE(created_at) = CURDATE()';
        $params = [
            'tid' => static::tenantId(),
            'uid' => $userId,
            'title' => $title,
            'url' => $url,
        ];
        if ($body !== null) {
            $sql .= ' AND body = :body';
            $params['body'] = $body;
        }
        return (int) static::db()->fetchColumn($sql, $params) > 0;
    }
}
