<?php

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

use Itgalaxy\PluginCommon\ActionSchedulerHelper;

class Cron
{
    public function __construct()
    {
        \add_action('init', [$this, 'createCron']);
        \add_action(Bootstrap::SEND_CRON_TASK, [$this, 'sendCronAction']);

        // not bind if run not cron mode
        if (!wp_doing_cron()) {
            return;
        }

        \add_action(Bootstrap::CRON, [$this, 'cronAction']);
    }

    /**
     * @return void
     */
    public function createCron()
    {
        if (!\wp_next_scheduled(Bootstrap::CRON)) {
            \wp_schedule_event(time(), 'weekly', Bootstrap::CRON);
        }
    }

    /**
     * @return void
     */
    public function cronAction()
    {
        $response = Bootstrap::$common->requester->call('cron_code_check');

        if (\is_wp_error($response)) {
            return;
        }

        if ($response->status === 'stop') {
            \update_site_option(Bootstrap::PURCHASE_CODE_OPTIONS_KEY, '');
        }
    }

    /**
     * @param string $optionName
     *
     * @return void
     */
    public function sendCronAction($optionName)
    {
        Helper::log('[cron/form] process start');

        $data = ActionSchedulerHelper::getDataForSendFormAction($optionName);

        if (empty($data)) {
            Helper::log('[cron/form] no data');

            return;
        }

        Crm::send($data['fields'], $data['settings'], $data['type']);

        Helper::log('[cron/form] process end');
    }
}
