<?php

namespace ScfPriceUpdater\Pages;

use ScfPriceUpdater\Assets;
use Timber\Timber;

abstract class AdminPage
{

    protected string $pageId;
    protected string $menuSlug;
    protected string $parentSlug;

    public function __construct(string $pageId, $parentSlug = 'toplevel')
    {
        $this->pageId = $pageId;
        $this->parentSlug = $parentSlug;

        add_action('admin_enqueue_scripts', [$this, 'enqueueScripts']);
        add_action('admin_menu', [$this, 'addAdminMenuItem']);

        if (isset($this->menuSlug)) {
            add_action('load-' . $parentSlug . '_page_' . $this->menuSlug, [$this, 'init']);
        }
    }

    abstract public function init();

    /**
     * Renders the page.
     * @return bool|string
     */
    public function renderPage()
    {
        $context = $this->buildTwigContext([
            'pluginUrl' => admin_url('admin.php?page='),
            'currentPage' => $_GET['page'],
        ]);
        return Timber::render("page-$this->pageId.twig", $context);
    }

    /**
     * @param array $context
     * @return mixed
     */
    abstract public function buildTwigContext(array $context = []);


    public function enqueueScripts($hook)
    {
        if ($hook === $this->parentSlug . '_page_' . $this->menuSlug) {
            Assets::enqueueCompiledScript('main');
            $this->enqueuePageScripts();
        }
    }

    /**
     * @return mixed
     */
    abstract public function enqueuePageScripts();

    abstract public function addAdminMenuItem();
}
