<?php

namespace BookneticApp\Providers\Core\Tasks;

use BookneticApp\Providers\Core\DotComApi;
use BookneticApp\Providers\Core\Tasks\Abstracts\TaskInterface;
use BookneticApp\Providers\Helpers\Helper;

class LicenseSyncTask implements TaskInterface
{
    public function canExecute(): bool
    {
        return Helper::processRuntimeController('license_check', 10 * 60 * 60);
    }

    public function execute(): void
    {
        Helper::setOption('license_last_checked_time', time(), false);

        $result = DotComApi::safeGet('get_notifications');

        if (empty($result['action'])) {
            return;
        }

        if ($result['action'] === 'empty') {
            Helper::setOption('plugin_alert', '', false);
            Helper::setOption('plugin_disabled', '0', false);
        } elseif ($result['action'] === 'warning') {
            if (! empty($result['message'])) {
                Helper::setOption('plugin_alert', $result['message'], false);
            }
            Helper::setOption('plugin_disabled', '0', false);
        } elseif ($result['action'] === 'disable') {
            if (! empty($result['message'])) {
                Helper::setOption('plugin_alert', $result['message'], false);
            }

            Helper::setOption('plugin_disabled', '1', false);
        } elseif ($result['action'] === 'error') {
            if (! empty($result['message'])) {
                Helper::setOption('plugin_alert', $result['message'], false);
            }

            Helper::setOption('plugin_disabled', '2', false);
        }

        if (! empty($result['remove_license'])) {
            Helper::deleteOption('purchase_code', false);
        }
    }

    public function getTaskName(): string
    {
        return 'license_sync';
    }
}
