<?php
/**
 * Hello World — Slate plugin bootstrap.
 *
 * Demonstrates the canonical patterns every plugin uses:
 *   - Extends Plugin, implements boot()
 *   - Registers admin nav via the admin_nav_items filter
 *   - Exposes a Public API class (HelloWorldAPI.php) for other
 *     plugins to call without touching this plugin's tables
 *   - Stores its own data in a slug-prefixed table
 *
 * Read this file alongside docs/PLUGIN-API.md before writing your
 * own plugin.
 */

class HelloWorld extends Plugin {

    public function boot(): void {
        // Register a sidebar nav item for the admin panel
        Hook::addFilter('admin_nav_items', [$this, 'addAdminNav']);

        // Optional: register a dashboard widget
        Hook::addFilter('admin_dashboard_widgets', [$this, 'addDashboardWidget']);

        // Load the Public API class (lazy — only when something asks for it)
        // by registering an autoload-style shim. Since we have no proper
        // autoloader in Slate, we just require it eagerly here; the class
        // file is tiny.
        $apiFile = $this->dir('HelloWorldAPI.php');
        if (file_exists($apiFile)) {
            require_once $apiFile;
        }
    }

    public function addAdminNav(array $items): array {
        $items[] = [
            'slug'  => 'hello-world',
            'label' => 'Hello World',
            'href'  => $this->url('admin/index.php'),
            'icon'  => 'star',
            'perm'  => 'hello.view',
            'order' => 500,
        ];
        return $items;
    }

    public function addDashboardWidget(array $widgets): array {
        $count = (int)Database::value(
            "SELECT COUNT(*) FROM helloworld_messages WHERE tenant_id = ?",
            [current_tenant_id()]
        );

        ob_start();
        ?>
        <div class="card">
            <div class="card-header">
                <h2>Hello World</h2>
                <span class="badge badge-active">active</span>
            </div>
            <p class="text-sub">
                The Hello World plugin is active. It has stored
                <strong><?= $count ?></strong> message<?= $count === 1 ? '' : 's' ?>
                in its own <code>helloworld_messages</code> table.
            </p>
            <a href="<?= e($this->url('admin/index.php')) ?>" class="btn btn-sm mt-2">
                Open Hello World →
            </a>
        </div>
        <?php
        $widgets[] = ob_get_clean();
        return $widgets;
    }
}
