<?php

namespace GriffinForms\Admin;

class DeactivationWarning extends \GriffinForms\Admin\Format
{
    private const SCRIPT_HANDLE = 'griffinforms-core-deactivation-warning';

    protected $package_state_resolver;

    public function __construct()
    {
        $this->setAll();
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
    }

    protected function setPackageStateResolver()
    {
        $this->package_state_resolver = \GriffinForms\Includes\Packages\PackageStateResolver::getInstance();
    }

    public function enqueueAssets($hook): void
    {
        if (!in_array($hook, ['plugins.php', 'plugins-network.php'], true)) {
            return;
        }

        $pro_state = $this->getProPackageState();
        if (!$this->shouldWarnForCoreDeactivation($pro_state)) {
            return;
        }

        wp_enqueue_script(
            self::SCRIPT_HANDLE,
            $this->config->getRootUrl() . 'admin/js/griffinforms-core-deactivation-warning.js',
            [],
            $this->config::JS_VER,
            true
        );

        wp_localize_script(self::SCRIPT_HANDLE, 'griffinformsCoreDeactivationWarning', [
            'core_plugin_basename' => plugin_basename($this->config->getRootPath() . 'griffinforms.php'),
            'pro_plugin_basename' => sanitize_text_field((string) ($pro_state['package_bootstrap_file'] ?? '')),
            'title' => __('Deactivate GriffinForms Core?', 'griffinforms-form-builder'),
            'message' => __('GriffinForms Pro is currently active and depends on GriffinForms Core. Deactivating Core will interrupt Pro runtime and move the site into an abnormal package state. Continue only if you intend to disable GriffinForms Pro behavior as well.', 'griffinforms-form-builder'),
        ]);
    }

    protected function getProPackageState(): array
    {
        $state = $this->package_state_resolver->getState();
        $packages = is_array($state['packages'] ?? null) ? $state['packages'] : [];

        return is_array($packages['pro'] ?? null) ? $packages['pro'] : [];
    }

    protected function shouldWarnForCoreDeactivation(array $pro_state): bool
    {
        return !empty($pro_state['is_present']) && !empty($pro_state['is_active']);
    }
}
