<?php

declare(strict_types=1);

namespace CloudXM\SDK\Admin;

use CloudXM\SDK\Templates\TemplateRendererInterface;

/**
 * Base class for all dashboard pages.  Handles capability checks, nonce output,
 * and template rendering so concrete pages stay tiny.
 */
abstract class AbstractAdminPage
{
    public function __construct(
        protected TemplateRendererInterface $renderer
    ) {}

    /** Entry-point wired into WordPress (e.g. add_submenu_page callback). */
    public function __invoke(): void
    {
        $this->guardCapability($this->capability());
        echo $this->renderer->fetch($this->template(), $this->data());
    }

    /* ---------------- Template methods for subclasses ---------------- */

    /** Required user capability (default manage_options). */
    protected function capability(): string
    {
        return 'manage_options';
    }

    /** Path (relative) of PHP template to render. */
    abstract protected function template(): string;

    /** Data array passed to template. */
    protected function data(): array
    {
        return [];
    }

    /* ------------------------------------------------------------------ */

    private function guardCapability(string $capability): void
    {
        if (!current_user_can($capability)) {
            wp_die(__('You do not have permission to view this page.', 'cloudxm-sdk'));
        }
    }
}
