<?php

declare(strict_types=1);

namespace BotGuard\Models;

use BotGuard\Core\Model;

/**
 * Administrator announcements surfaced as dashboard banners.
 */
final class Announcement extends Model
{
    protected string $table = 'announcements';

    public const LEVELS = ['info', 'success', 'warning', 'danger'];

    /**
     * Currently-visible announcements: active and within their optional window.
     *
     * @return array<int, array<string, mixed>>
     */
    public function activeNow(): array
    {
        $now = now();

        return $this->db->select(
            "SELECT * FROM `{$this->table}`
             WHERE `active` = 1
               AND (`starts_at` IS NULL OR `starts_at` <= ?)
               AND (`ends_at` IS NULL OR `ends_at` >= ?)
             ORDER BY `id` DESC",
            [$now, $now]
        );
    }

    public function toggleActive(int $id): int
    {
        return $this->db->affectingStatement(
            "UPDATE `{$this->table}` SET `active` = 1 - `active` WHERE `id` = ?",
            [$id]
        );
    }

    public static function isValidLevel(string $level): bool
    {
        return in_array($level, self::LEVELS, true);
    }
}
