<?php
/**
 * Hello World — Public API.
 *
 * Other plugins call HelloWorldAPI::* — never read or write
 * `helloworld_messages` directly. This class is the contract.
 *
 * Usage from another plugin:
 *
 *   if (PluginLoader::isActive('hello-world') && class_exists('HelloWorldAPI')) {
 *       $latest = HelloWorldAPI::getLatestMessage();
 *   }
 */

class HelloWorldAPI {

    /**
     * Return the most recent message, or null if none.
     */
    public static function getLatestMessage(?int $tenantId = null): ?array {
        $tenantId = $tenantId ?? current_tenant_id();
        return Database::row(
            "SELECT id, message, created_at
             FROM helloworld_messages
             WHERE tenant_id = ?
             ORDER BY id DESC
             LIMIT 1",
            [$tenantId]
        );
    }

    /**
     * Add a new message. Returns the new id.
     */
    public static function addMessage(string $message, ?int $tenantId = null): int {
        $tenantId = $tenantId ?? current_tenant_id();
        return Database::insert('helloworld_messages', [
            'tenant_id' => $tenantId,
            'message'   => mb_substr(trim($message), 0, 255),
        ]);
    }

    /**
     * Count messages for a tenant.
     */
    public static function countMessages(?int $tenantId = null): int {
        $tenantId = $tenantId ?? current_tenant_id();
        return (int)Database::value(
            "SELECT COUNT(*) FROM helloworld_messages WHERE tenant_id = ?",
            [$tenantId]
        );
    }
}
