<?php
/**
 * Hello World — admin page.
 *
 * Demonstrates the canonical pattern every plugin admin page follows:
 *   1. Require config.php (three dirname()s — admin/ inside hello-world/
 *      inside plugins/ inside SLATE_ROOT)
 *   2. Auth::require()
 *   3. Auth::requirePerm('hello.view') — declared in plugin.json
 *   4. Set $pageTitle and $currentNav
 *   5. Include the shared admin header / footer
 *
 * Plugins don't render any chrome — the shell does the sidebar, topbar,
 * mobile tab bar, and CSS. Plugins just write their content using the
 * shared design system (.card, .btn, .field, etc).
 */
require_once dirname(__DIR__, 3) . '/config.php';

Auth::require();
Auth::requirePerm('hello.view');

$pageTitle  = 'Hello World';
$currentNav = 'hello-world';

// ── Handle "add message" POST ────────────────────────────────
$flash = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && Auth::can('hello.manage')) {
    if (!csrf_verify()) {
        $flash = ['type' => 'error', 'msg' => 'Security check failed.'];
    } else {
        $msg = trim($_POST['message'] ?? '');
        if ($msg === '') {
            $flash = ['type' => 'error', 'msg' => 'Message cannot be empty.'];
        } else {
            HelloWorldAPI::addMessage($msg);
            $flash = ['type' => 'success', 'msg' => 'Message added.'];
        }
    }
}

// ── Load data ────────────────────────────────────────────────
$messages = Database::rows(
    "SELECT id, message, created_at FROM helloworld_messages
     WHERE tenant_id = ? ORDER BY id DESC LIMIT 20",
    [current_tenant_id()]
);

require SLATE_ROOT . '/admin/partials/header.php';
?>

<?php slate_breadcrumbs([
    ['label' => 'Dashboard', 'href' => SLATE_URL . '/admin/'],
    ['label' => 'Hello World'],
]); ?>

<div class="page-header">
    <div>
        <h1>Hello, World!</h1>
        <p class="page-header-sub">
            This page is rendered by the <code>hello-world</code> plugin.
        </p>
    </div>
    <span class="badge badge-active">plugin is alive</span>
</div>

<?php if ($flash): ?>
    <div class="alert alert-<?= e($flash['type']) ?>" role="status"><?= e($flash['msg']) ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2>How this works</h2>
    </div>
    <p class="text-sub">
        If you can see this page, the Slate plugin loader is working —
        the plugin was installed, activated, and is being booted on every
        request. It registered itself in the sidebar via a hook filter and
        is reading from its own database table.
    </p>
</div>

<?php if (Auth::can('hello.manage')): ?>
<div class="card">
    <div class="card-header">
        <h2>Add a message</h2>
    </div>
    <form method="post">
        <?= csrf_field() ?>
        <div class="field">
            <label class="field-label" for="message">Message</label>
            <input type="text" id="message" name="message" maxlength="255" required
                   placeholder="Anything you like — this gets saved to helloworld_messages">
        </div>
        <button type="submit" class="btn btn-primary">Add message</button>
    </form>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2>Stored messages</h2>
        <span class="text-muted text-sm"><?= count($messages) ?> shown</span>
    </div>
    <?php if (!$messages): ?>
        <div class="empty">
            <div class="empty-title">No messages yet</div>
            <p>Add one above to see it appear here.</p>
        </div>
    <?php else: ?>
        <div class="data-list" data-single-open>
            <?php foreach ($messages as $m):
                slate_data_row([
                    'avatar'       => '#' . (int)$m['id'],
                    'avatar_color' => 'info',
                    'title'        => $m['message'],
                    'meta'         => 'Stored ' . $m['created_at'],
                    'detail'       => [
                        'ID'        => (int)$m['id'],
                        'Message'   => $m['message'],
                        'Created'   => $m['created_at'],
                    ],
                ]);
            endforeach; ?>
        </div>
        <?php slate_data_list_script(); ?>
    <?php endif; ?>
</div>

<?php require SLATE_ROOT . '/admin/partials/footer.php'; ?>
