<?php
class QuickLink
{
    public static function all(): array
    {
        Database::migrate();
        $stmt = Database::pdo()->query('SELECT * FROM quick_links ORDER BY is_active DESC, name ASC');
        return $stmt->fetchAll();
    }

    public static function active(): array
    {
        Database::migrate();
        $stmt = Database::pdo()->query('SELECT * FROM quick_links WHERE is_active = 1 ORDER BY name ASC');
        return $stmt->fetchAll();
    }

    public static function save(array $data): array
    {
        Database::migrate();
        $id = (int)($data['link_id'] ?? 0);
        $name = trim($data['name'] ?? '');
        $url = trim($data['url'] ?? '');
        $notes = trim($data['notes'] ?? '');
        if ($name === '' || $url === '') {
            return ['ok' => false, 'message' => 'Informe nome e link do site.'];
        }
        if (!preg_match('#^https?://#i', $url)) {
            $url = 'https://' . $url;
        }
        if ($id > 0) {
            $stmt = Database::pdo()->prepare('UPDATE quick_links SET name = ?, url = ?, notes = ? WHERE id = ?');
            $stmt->execute([$name, $url, $notes, $id]);
            return ['ok' => true, 'message' => 'Link atualizado.'];
        }
        $stmt = Database::pdo()->prepare('INSERT INTO quick_links (name, url, notes, is_active, created_at) VALUES (?, ?, ?, 1, ?)');
        $stmt->execute([$name, $url, $notes, date('Y-m-d H:i:s')]);
        return ['ok' => true, 'message' => 'Link salvo com sucesso.'];
    }

    public static function toggle(int $id): bool
    {
        Database::migrate();
        $stmt = Database::pdo()->prepare('UPDATE quick_links SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->rowCount() > 0;
    }

    public static function delete(int $id): bool
    {
        Database::migrate();
        $stmt = Database::pdo()->prepare('DELETE FROM quick_links WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->rowCount() > 0;
    }
}
