<?php

namespace Itgalaxy\Elementor\Form\Infusionsoft\Integration\Admin\AjaxActions;

use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes\Bootstrap;
use Itgalaxy\PluginCommon\AdminGenerator\Themes\DefaultTheme;

class LicenseAjaxAction
{
    /**
     * @var string
     */
    public static $name = 'itglx/elpro/keap/license';

    public function __construct()
    {
        add_action('wp_ajax_' . self::$name, [$this, 'action']);
    }

    /**
     * @return void
     */
    public function action()
    {
        if (!current_user_can('manage_options')) {
            exit;
        }

        if (isset($_POST['code'])) {
            $response = Bootstrap::$common->requester->code(
                isset($_POST['type']) && $_POST['type'] === 'verify' ? 'code_activate' : 'code_deactivate',
                trim(wp_unslash($_POST['code']))
            );

            if ($response['state'] == 'successCheck') {
                DefaultTheme::callout(esc_html($response['message']), 'success');
            } elseif ($response['message']) {
                DefaultTheme::callout(esc_html($response['message']), 'danger');
            }
        }

        DefaultTheme::licenseBlock(
            \get_site_option(Bootstrap::PURCHASE_CODE_OPTIONS_KEY, ''),
            self::$name
        );

        exit;
    }
}
