<?php

namespace Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes;

use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Admin\IntegrationSettings;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Admin\LogHelper;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Admin\PluginActionLinksFilter;
use Itgalaxy\PluginCommon\AnalyticsHelper;
use Itgalaxy\PluginCommon\CacheHelper;
use Itgalaxy\PluginCommon\MainHelperLoader;

class Bootstrap
{
    const PLUGIN_ID = '33704547';
    const PLUGIN_VERSION = '1.6.0';

    const OPTIONS_KEY = 'elementor-infusionsoft-integration-settings';
    const PURCHASE_CODE_OPTIONS_KEY = 'elementor-infusionsoft-purchase-code';
    const TOKEN_KEY = 'elementor-infusionsoft-token';
    const REFRESH_TOKEN_KEY = 'elementor-infusionsoft-refresh-token';

    const CONTACT_CUSTOM_FIELDS_KEY = '_elementor-infusionsoft-custom-contact';

    const SEND_CRON_TASK = 'elementor-infusionsoft-integration-send-cron-task';
    const CRON = 'elementor-infusionsoft-cron';
    const UTM_COOKIES = 'elementor-infusionsoft-utm-cookie';

    /**
     * @var string Absolute path (with a trailing slash) to the plugin directory.
     */
    public static $pluginDir;

    /**
     * @var string URL to the plugin directory (with a trailing slash).
     */
    public static $pluginUrl;

    /**
     * @var string Absolute path to the file for log content.
     */
    public static $pluginLogFile;

    /**
     * @var MainHelperLoader
     */
    public static $common;

    /**
     * @var string
     */
    public static $plugin = '';

    /**
     * @var null|Bootstrap
     */
    private static $instance;

    /**
     * @param string $file
     */
    protected function __construct($file)
    {
        if (!defined('EL_PRO_FORM_INFUSIONSOFT_PLUGIN_LOG_FILE')) {
            define('EL_PRO_FORM_INFUSIONSOFT_PLUGIN_LOG_FILE', \wp_upload_dir()['basedir'] . '/logs/.elproinfsoft.log');
        }

        self::$plugin = $file;
        self::$pluginDir = \plugin_dir_path(self::$plugin);
        self::$pluginUrl = \plugin_dir_url(self::$plugin);
        self::$pluginLogFile = EL_PRO_FORM_INFUSIONSOFT_PLUGIN_LOG_FILE;
        self::$common = new MainHelperLoader($this);

        self::pluginLifeCycleActionsRegister();
        $this->init();

        \add_action('init', [$this, 'utmCookies']);
        \add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);

        \add_action('wp_ajax_itglx/elpro/keap/set/utm', [$this, 'utmCookies']);
        \add_action('wp_ajax_nopriv_itglx/elpro/keap/set/utm', [$this, 'utmCookies']);
    }

    /**
     * @param string $file
     *
     * @return null|Bootstrap
     */
    public static function getInstance($file)
    {
        if (!self::$instance) {
            self::$instance = new self($file);
        }

        return self::$instance;
    }

    /**
     * @return void
     */
    public function init()
    {
        new Cron();

        if (\is_admin()) {
            \add_action('init', function () {
                new LogHelper();
                new PluginActionLinksFilter();
            });

            \add_action('elementor_pro/init', function () {
                new IntegrationSettings();
            });
        }

        new FormActionsLoader();
    }

    /**
     * @return void
     */
    public static function pluginLifeCycleActionsRegister()
    {
        /**
         * @see https://developer.wordpress.org/reference/functions/register_activation_hook/
         */
        \register_activation_hook(self::$plugin, [self::class, 'pluginActivation']);

        /**
         * @see https://developer.wordpress.org/reference/functions/register_deactivation_hook/
         */
        \register_deactivation_hook(self::$plugin, [self::class, 'pluginDeactivation']);
    }

    /**
     * @return void
     */
    public static function pluginActivation()
    {
        self::$common->requester->call('plugin_activate');
        self::$common->logger->prepare();
    }

    /**
     * @return void
     */
    public static function pluginDeactivation()
    {
        self::$common->requester->call('plugin_deactivate');
        \wp_clear_scheduled_hook(self::CRON);
    }

    /**
     * @return void
     */
    public static function pluginUninstall()
    {
        self::$common->requester->call('plugin_uninstall');
    }

    /**
     * @return void
     */
    public function utmCookies()
    {
        $utmParams = AnalyticsHelper::getUtmListFromUrl();

        if (!empty($utmParams)) {
            setcookie(self::UTM_COOKIES, \wp_json_encode($utmParams), time() + 86400, '/');
        }
    }

    /**
     * @return void
     */
    public function enqueueScripts()
    {
        if (!CacheHelper::siteUsesCache()) {
            return;
        }

        \wp_enqueue_script('elementor-keap-theme', self::$common->assetsHelper->getPathAssetFile('/theme/js/app.js'), [], null, true);
    }
}
