<?php

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

use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Admin\AjaxActions\LicenseAjaxAction;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Admin\AjaxActions\LogAjaxAction;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Admin\PageParts\AuthorizePagePart;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Admin\PageParts\HeaderPagePart;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Admin\PageParts\ReloadFieldsPagePart;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes\Bootstrap;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes\Crm;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes\RequestHelper;
use Itgalaxy\PluginCommon\AdminGenerator\Elements\Root;
use Itgalaxy\PluginCommon\AdminGenerator\Themes\DefaultTheme;

class IntegrationSettings
{
    public function __construct()
    {
        add_action('admin_menu', [$this, 'addSubmenu'], 801); // 800 - it is license menu item priority
        add_action('init', [$this, 'submitListener']);
        add_action('admin_notices', [$this, 'notice']);

        if (isset($_GET['page']) && $_GET['page'] === Bootstrap::OPTIONS_KEY) {
            add_action('admin_enqueue_scripts', function () {
                DefaultTheme::enqueueStyle();
                DefaultTheme::enqueueScript();
            });
        }

        new LicenseAjaxAction();
        new LogAjaxAction();
    }

    /**
     * @return void
     */
    public function notice()
    {
        if (\get_site_option(Bootstrap::PURCHASE_CODE_OPTIONS_KEY)) {
            return;
        }

        echo sprintf(
            '<div class="notice notice-error" data-ui-component="itglx-license-notice"><p><strong>%1$s</strong>: %2$s <a href="%3$s">%4$s</a></p></div>',
            esc_html__('Elementor Pro Form Widget - Keap', 'el-pro-form-infusionsoft-integration'),
            esc_html__(
                'Please verify the purchase code on the plugin settings page - ',
                'el-pro-form-infusionsoft-integration'
            ),
            esc_url(admin_url() . 'admin.php?page=' . Bootstrap::OPTIONS_KEY . '#itglx-license-verify'),
            esc_html__('open', 'el-pro-form-infusionsoft-integration')
        );
    }

    /**
     * @return void
     */
    public function addSubmenu()
    {
        add_submenu_page(
            'elementor',
            esc_html__('Infusionsoft', 'el-pro-form-infusionsoft-integration'),
            esc_html__('Infusionsoft', 'el-pro-form-infusionsoft-integration'),
            'manage_options',
            Bootstrap::OPTIONS_KEY,
            [$this, 'settingsPage']
        );
    }

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

        if (!empty($_GET['page']) && $_GET['page'] === Bootstrap::OPTIONS_KEY && !empty($_GET['code'])) {
            $option = get_option(Bootstrap::OPTIONS_KEY, []);
            $option['code'] = wp_unslash($_GET['code']);

            update_option(Bootstrap::OPTIONS_KEY, $option);

            // reset old token
            update_option(Bootstrap::TOKEN_KEY, '');
            update_option(Bootstrap::REFRESH_TOKEN_KEY, '');

            $result = RequestHelper::checkConnection();

            if ($result) {
                $option = get_option(Bootstrap::OPTIONS_KEY);
                unset($option['code']);
                update_option(Bootstrap::OPTIONS_KEY, $option);

                Crm::updateInformation();

                wp_safe_redirect(admin_url() . 'admin.php?page=' . Bootstrap::OPTIONS_KEY . '&success');

                exit;
            }
        }

        if (isset($_POST['elementorInfusionsoftReloadFieldsCache'])) {
            Crm::updateInformation();

            wp_safe_redirect(admin_url() . 'admin.php?page=' . Bootstrap::OPTIONS_KEY . '&success-fields-reload');

            exit;
        }

        if (!isset($_POST['elementorInfusionsoftSubmit'])) {
            return;
        }

        $apiKey = isset($_POST['api-key']) ? trim(wp_unslash($_POST['api-key'])) : '';
        $apiSecret = isset($_POST['api-secret']) ? trim(wp_unslash($_POST['api-secret'])) : '';

        // reset old token
        update_option(Bootstrap::TOKEN_KEY, '');
        update_option(Bootstrap::REFRESH_TOKEN_KEY, '');

        if (empty($apiKey) || empty($apiSecret)) {
            $option = get_option(Bootstrap::OPTIONS_KEY, []);
            $option['api-key'] = '';
            $option['api-secret'] = '';

            update_option(Bootstrap::OPTIONS_KEY, $option);

            wp_safe_redirect(admin_url() . 'admin.php?page=' . Bootstrap::OPTIONS_KEY . '&error-required-fields');

            exit;
        }

        $settings = get_option(Bootstrap::OPTIONS_KEY, []);

        update_option(
            Bootstrap::OPTIONS_KEY,
            [
                'api-key' => $apiKey,
                'api-secret' => $apiSecret,
                'enabled_logging' => isset($settings['enabled_logging']) ? $settings['enabled_logging'] : '',
                'send_type' => isset($_POST['send_type']) ? trim(wp_unslash($_POST['send_type'])) : '',
            ]
        );

        wp_redirect(
            'https://accounts.infusionsoft.com/app/oauth/authorize?'
            . 'scope=full'
            . '&client_id='
            . $apiKey
            . '&response_type=code'
            . '&redirect_uri='
            . admin_url()
            . urlencode('admin.php?page=' . Bootstrap::OPTIONS_KEY)
        );

        exit;
    }

    /**
     * @return void
     */
    public function settingsPage()
    {
        DefaultTheme::rootWrapperStart();

        // generate base js variables
        Root::render(['type' => 'options']);

        HeaderPagePart::render();
        AuthorizePagePart::render();
        ReloadFieldsPagePart::render();

        $settings = get_option(Bootstrap::OPTIONS_KEY, []);

        DefaultTheme::logsBlock(
            [
                'enabled' => !empty($settings['enabled_logging']),
                'enableAction' => LogAjaxAction::$enableLogActionName,
                'downloadUrl' => admin_url() . '?' . Bootstrap::OPTIONS_KEY . '-logs-get=' . uniqid(),
                'clearAction' => LogAjaxAction::$clearLogActionName,
                'filePath' => Bootstrap::$pluginLogFile,
            ]
        );

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

        DefaultTheme::rootWrapperEnd();
    }
}
