<?php
namespace Tiamr\Admin;

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

final class Assets {
    public function __construct() {
        add_action('admin_enqueue_scripts', [$this, 'enqueue']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_global_menu_style']);
    }


    public function enqueue_global_menu_style(): void {
        wp_register_style(
            'titanium-amr-upgrade-menu-style',
            false,
            [],
            TIAMR_VERSION
        );
        wp_enqueue_style('titanium-amr-upgrade-menu-style');
        wp_add_inline_style(
            'titanium-amr-upgrade-menu-style',
            '#adminmenu .amr-upgrade-menu-label{color:#16a34a!important;font-weight:800!important;}#adminmenu a:hover .amr-upgrade-menu-label,#adminmenu .current .amr-upgrade-menu-label,#adminmenu a.wp-has-current-submenu .amr-upgrade-menu-label{color:#15803d!important;}#adminmenu .amr-upgrade-menu-label::before{content:"";display:inline-block;width:6px;height:6px;margin:0 7px 1px 0;border-radius:999px;background:#16a34a;vertical-align:middle;}'
        );
    }

    public function enqueue(string $hook_suffix): void {
        $is_menu_editor = 'nav-menus.php' === $hook_suffix;
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin page detection only; no form data is processed here.
        $current_page   = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

        $plugin_page_slugs = [
            'titanium-advanced-menu-rules',
            'titanium-advanced-menu-rules-settings',
            'titanium-advanced-menu-rules-upgrade',
            'titanium-advanced-menu-rules-license-activation',
        ];

        $plugin_page_hooks = [
            'toplevel_page_titanium-advanced-menu-rules',
            'titanium-advanced-menu-rules_page_titanium-advanced-menu-rules',
            'titanium-advanced-menu-rules_page_titanium-advanced-menu-rules-settings',
            'titanium-advanced-menu-rules_page_titanium-advanced-menu-rules-upgrade',
            'admin_page_titanium-advanced-menu-rules-license-activation',
        ];

        $is_plugin_page = in_array($hook_suffix, $plugin_page_hooks, true) || in_array($current_page, $plugin_page_slugs, true);
        $is_pricing_page = 'titanium-advanced-menu-rules-upgrade' === $current_page || false !== strpos($hook_suffix, 'titanium-advanced-menu-rules-upgrade');

        if (!$is_menu_editor && !$is_plugin_page) {
            return;
        }

        wp_enqueue_style(
            'titanium-advanced-menu-rules-admin',
            TIAMR_PLUGIN_URL . 'assets/admin.css',
            [],
            $this->asset_version('assets/admin.css')
        );

        if ($is_pricing_page) {
            wp_enqueue_script(
                'titanium-advanced-menu-rules-pricing',
                TIAMR_PLUGIN_URL . 'assets/pricing.js',
                [],
                $this->asset_version('assets/pricing.js'),
                true
            );

            wp_localize_script(
                'titanium-advanced-menu-rules-pricing',
                'tiamrPricing',
                [
                    'ajaxUrl'  => admin_url('admin-ajax.php'),
                    'action'   => 'tiamr_get_freemius_pricing',
                    'button'   => __('UPGRADE NOW', 'titanium-advanced-menu-rules'),
                    'perYear'  => __('/ year', 'titanium-advanced-menu-rules'),
                    'strings'  => [
                        'loadingPrices'     => __('Loading prices...', 'titanium-advanced-menu-rules'),
                        'pricesUnavailable' => __('Unable to load prices. Secure checkout will show the current price.', 'titanium-advanced-menu-rules'),
                        'checkoutPrice'     => __('Price shown at secure checkout', 'titanium-advanced-menu-rules'),
                    ],
                ]
            );
        }

        if ($is_plugin_page) {
            wp_enqueue_script(
                'titanium-advanced-menu-rules-settings',
                TIAMR_PLUGIN_URL . 'assets/settings.js',
                [],
                $this->asset_version('assets/settings.js'),
                true
            );

            wp_localize_script(
                'titanium-advanced-menu-rules-settings',
                'tiamrSettings',
                [
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'nonce'   => wp_create_nonce('tiamr_save_setting'),
                    'action'  => 'tiamr_save_setting',
                    'delay'   => 500,
                    'beta'   => $this->get_beta_settings_for_js(),
                    'strings' => [
                        'saving' => __('Saving...', 'titanium-advanced-menu-rules'),
                        'saved'  => __('Saved', 'titanium-advanced-menu-rules'),
                        'failed' => __('Could not save. Please try again.', 'titanium-advanced-menu-rules'),
                        'selectPageFirst' => __('Select a page before saving.', 'titanium-advanced-menu-rules'),
                    ],
                ]
            );
        }

        if (!$is_menu_editor) {
            return;
        }

        wp_enqueue_script(
            'titanium-advanced-menu-rules-admin',
            TIAMR_PLUGIN_URL . 'assets/admin.js',
            ['jquery'],
            $this->asset_version('assets/admin.js'),
            true
        );

        wp_localize_script(
            'titanium-advanced-menu-rules-admin',
            'tiamrAdmin',
            [
                'ajaxUrl'       => admin_url('admin-ajax.php'),
                'searchNonce'   => wp_create_nonce('tiamr_search_content'),
                'typeMoreChars' => __('Type at least 2 characters.', 'titanium-advanced-menu-rules'),
                'noResults'     => __('No results found.', 'titanium-advanced-menu-rules'),
                'searching'     => __('Searching...', 'titanium-advanced-menu-rules'),
            ]
        );
    }
    private function get_beta_settings_for_js(): array {
        $settings = [
            'native' => false,
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'action' => '',
            'security' => '',
            'moduleId' => 0,
            'confirm' => __('Beta updates can replace your installed version with a beta release. Use with caution on production sites. Continue?', 'titanium-advanced-menu-rules'),
        ];

        if (function_exists('tiamr_fs')) {
            $fs = tiamr_fs();

            if (
                is_object($fs) &&
                method_exists($fs, 'get_ajax_action') &&
                method_exists($fs, 'get_ajax_security') &&
                method_exists($fs, 'get_id') &&
                defined('TIAMR_PRO_FEATURES_ACTIVE') && TIAMR_PRO_FEATURES_ACTIVE
            ) {
                $settings['native'] = true;
                $settings['action'] = $fs->get_ajax_action('set_beta_mode');
                $settings['security'] = $fs->get_ajax_security('set_beta_mode');
                $settings['moduleId'] = $fs->get_id();
            }
        }

        return $settings;
    }


    private function asset_version(string $relative_path): string {
        $file = TIAMR_PLUGIN_DIR . ltrim($relative_path, '/');

        if (is_readable($file)) {
            return TIAMR_VERSION . '-' . (string) filemtime($file);
        }

        return TIAMR_VERSION;
    }

}
