<?php

namespace core;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}


/**
 * Abstract class for creating option pages in WP admin.
 */
abstract class OptionAbstract
{
    protected $slug;
    protected $title;
    protected $parent_slug;
    protected $option_group;
    protected $option_args = []; // [name => [type, label, description, default]]

    public function __construct($slug, $title, $option_group, $option_items)
    {
        $this->slug = $slug;
        $this->title = $title;
        $this->option_group = $option_group;
        $this->option_args = $option_items;

        add_action('admin_menu', [$this, 'register_page']);
        add_action('admin_init', [$this, 'on_init']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
    }

    // Registers the options page in WP admin
    public function register_page()
    {
        add_options_page(
            $this->title['page']?:'',
            $this->title['menu']?:'',
            'manage_options',
            $this->slug,
            [$this, 'render_page']
        );
    }

    // Registers each option setting
    private function register_settings()
    {
        foreach( $this->option_args as $name => $arg ) {
            register_setting($this->option_group, $name, $arg);
        }
    }

    public function enqueue_scripts($hook)
    {
        if (strpos($hook, $this->slug) !== false) {
            $this->enqueue_scripts_internal($hook);
        }
    }

    // The actual admin page HTML
    public function render_page()
    {
        echo "<div class='wrap'>";
        echo "<h2>" . esc_html($this->title['page']?:'') . "</h2>";
        $this->render_page_internal();
        echo "</div>";
    }

    public function on_init(): void
    {
        if (
            isset($_POST['option_page']) &&
            $_POST['option_page'] === $this->option_group &&
            check_admin_referer($this->option_group . '-options')
        ) {
            add_action('shutdown', [$this, 'on_shutdown'], 10, 0);
            $this->register_settings();
            $this->init_internal();
        }
    }
    public function on_shutdown(): void
    {
        $this->shutdown_internal();
    }

    // Override
    abstract protected function enqueue_scripts_internal($hook);
    abstract protected function render_page_internal();
    abstract protected function init_internal(): void;
    abstract protected function shutdown_internal(): void;

}

