<?php
/**
 * WordPress admin integration.
 *
 * @package BatoCookieConsent
 */

if (! defined('ABSPATH')) {
    exit;
}

final class Bato_Cookie_Consent_Admin
{
    private Bato_Cookie_Consent_Settings $settings;
    private array $hook_suffixes = array();

    public function __construct(Bato_Cookie_Consent_Settings $settings)
    {
        $this->settings = $settings;
    }

    public function init(): void
    {
        add_action('admin_menu', array($this, 'register_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
    }

    public function register_menu(): void
    {
        $this->hook_suffixes[] = add_menu_page(
            __('Cookie Consent', 'bato-cookie-consent'),
            __('Cookie Consent', 'bato-cookie-consent'),
            'manage_options',
            'bato-cookie-consent',
            array($this, 'render_page'),
            'dashicons-privacy',
            81
        );

        foreach ($this->editor_tabs() as $tab => $label) {
            $this->hook_suffixes[] = add_submenu_page(
                'bato-cookie-consent',
                $label,
                $label,
                'manage_options',
                $this->menu_slug_for_tab($tab),
                array($this, 'render_page')
            );
        }
    }

    public function render_page(): void
    {
        if (! current_user_can('manage_options')) {
            return;
        }

        echo '<div class="wrap bato-cookie-consent-admin">';
        echo '<div id="bato-cookie-consent-admin-root"></div>';
        echo '</div>';
    }

    public function enqueue_assets(string $hook_suffix): void
    {
        if (! $this->is_editor_page($hook_suffix)) {
            return;
        }

        wp_enqueue_media();

        $asset_file = BATO_COOKIE_CONSENT_PATH . 'assets/admin.asset.php';
        $asset = file_exists($asset_file)
            ? include $asset_file
            : array('dependencies' => array('wp-i18n', 'wp-api-fetch'), 'version' => BATO_COOKIE_CONSENT_VERSION);

        wp_enqueue_script(
            'bato-cookie-consent-admin',
            BATO_COOKIE_CONSENT_URL . 'assets/admin.js',
            $asset['dependencies'],
            $asset['version'],
            true
        );

        wp_enqueue_style(
            'bato-cookie-consent-admin',
            BATO_COOKIE_CONSENT_URL . 'assets/admin.css',
            array(),
            $asset['version']
        );

        wp_set_script_translations(
            'bato-cookie-consent-admin',
            'bato-cookie-consent',
            BATO_COOKIE_CONSENT_PATH . 'languages'
        );

        wp_localize_script(
            'bato-cookie-consent-admin',
            'BatoCookieConsentAdmin',
            array(
                'restUrl' => esc_url_raw(rest_url('bato-cookie-consent/v1')),
                'nonce' => wp_create_nonce('wp_rest'),
                'settings' => $this->settings->get(),
                'defaults' => Bato_Cookie_Consent_Settings::defaults(),
                'meta' => $this->settings->metadata(),
                'adminLogoUrl' => esc_url_raw(BATO_COOKIE_CONSENT_URL . 'assets/bato-cookie-consent.svg'),
                'currentTab' => $this->current_tab(),
                'tabs' => $this->editor_tabs(),
            )
        );
    }

    private function is_editor_page(string $hook_suffix): bool
    {
        if (in_array($hook_suffix, array_filter($this->hook_suffixes), true)) {
            return true;
        }

        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        return in_array($page, array_map(array($this, 'menu_slug_for_tab'), array_keys($this->editor_tabs())), true);
    }

    private function editor_tabs(): array
    {
        return array(
            'general' => __('General', 'bato-cookie-consent'),
            'content' => __('Content', 'bato-cookie-consent'),
            'links' => __('Policy Links', 'bato-cookie-consent'),
            'styling' => __('Styling', 'bato-cookie-consent'),
            'docs' => __('Scripts / Embeds', 'bato-cookie-consent'),
            'api' => __('API Reference', 'bato-cookie-consent'),
            'settings' => __('Settings', 'bato-cookie-consent'),
        );
    }

    private function menu_slug_for_tab(string $tab): string
    {
        return 'general' === $tab ? 'bato-cookie-consent' : 'bato-cookie-consent-' . $tab;
    }

    private function current_tab(): string
    {
        $tabs = array_keys($this->editor_tabs());
        $requested_tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        if (in_array($requested_tab, $tabs, true)) {
            return $requested_tab;
        }

        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        foreach ($tabs as $tab) {
            if ($this->menu_slug_for_tab($tab) === $page) {
                return $tab;
            }
        }

        return 'general';
    }
}
