<?php

namespace RTMCustomMails\Pages;

use WordpressModels\Assets;
use WordpressModels\Page\AbstractPage;
use WordpressModels\Page\AbstractPageStack;

/**
 * Reimplementation of the Page class to add the admin menu item, like in wordpress-models pre-0.6
 */
abstract class PageStack extends AbstractPageStack
{

    public function __construct(string $pageId, string $menuSlug, string $title, AbstractPage|string $parent = 'toplevel', string $capability = 'administrator', int|string|null $position = null, string $icon = '', array $additionalScripts = [], ?Assets $assets = null)
    {
        parent::__construct($pageId, $menuSlug, $title, $parent, $capability, $position, $icon, $additionalScripts, $assets);        add_action('admin_menu', $this->addAdminMenuItem(...));
        add_action('admin_menu', $this->addAdminMenuItem(...));
    }

    public function addAdminMenuItem(): void
    {
        if ($this->parent !== 'toplevel') {
            $this->pageLoadHook = add_submenu_page(
                $this->parent instanceof AbstractPage ? $this->parent->getMenuSlug() : $this->parent,
                $this->title,
                $this->title,
                $this->capability,
                $this->menuSlug,
                $this->renderCallback,
                $this->position ?: '0'
            );
        } else {
            $this->pageLoadHook = add_menu_page(
                $this->title,
                $this->title,
                $this->capability,
                $this->menuSlug,
                $this->renderCallback,
                $this->icon,
                $this->position ?: '0'
            );
        }

        if ($this->pageLoadHook) {
            add_action('load-' . $this->pageLoadHook, $this->init(...));
        }
    }

}