<?php
namespace ONLINE_ADAv4\Services;

use ONLINE_ADAv4\Plugin;
use ONLINE_ADAv4\Services\License;

class Options {
    
    use \ONLINE_ADAv4\Traits\Singleton;

    public function __construct(){
    }

    public function updateOptions($request){
        $response = [];
        foreach($request['options'] AS $key => $value){
            update_option($key, $value);
            if($key == Plugin::instance()->info['license_key']){
                $checkResponse = License::getInstance()->check(['license' => $value]);
                
                $message = $this->doActionOnResponse($checkResponse, $value);
                $response['license_status'] = filter_var(get_option(Plugin::instance()->info['license_status_key'],true),FILTER_VALIDATE_BOOLEAN);
                $response['license_message'] = $message;
            }
        }
        return $response;
    }
    public function getOptions($request){
        $options = [];
        foreach($request['keys'] AS $key) {
            $options[$key] = get_option($key, '');
        }
        return $options;
    }
    public function doActionOnResponse($response,$license) {
        if(isset($response['migrate_flag'])) {
            update_option(Plugin::instance()->info['migration_key'], $response['migrate_flag']);
        }
        if( strpos($response['message'],'Domain Inactive') !== false) {
            $response = License::getInstance()->activate(['license' => $license]);
        }
        if(strpos($response['message'], "This is not a valid license") !== false){
            update_option(Plugin::instance()->info["license_status_key"], 0);
        }
        return $response['message'];
    }
}