<?php

if (!defined('ABSPATH')) {
    exit;
}

class SchematicApi {

    protected $url = 'https://api.schemaplugin.net/api/';

    public function __construct() {
        add_action('wp_ajax_schematic_verify_api_key', array($this, 'verify_api_key'));
        add_action('wp_ajax_schematic_update_license_data', array($this, 'update_license_data'));
        add_action('wp_ajax_schematic_save_license_data', array($this, 'save_license_data'));
    }

    public function getUrl() {

        if (defined('WPSCHEMA_API_URL') && strpos(WPSCHEMA_API_URL, '.schemaplugin.') !== false) {
            return WPSCHEMA_API_URL;
        }

        return $this->url;
    }

    public function save_license_data() {
        if (current_user_can('administrator')) {
            check_ajax_referer('schematic-nonce');

            if ($_POST['key']) {
                $array = array('key' => strip_tags($_POST['key']), 'flag' => $this->to_bool($_POST['flag']));

                update_option('_schematic_d_l', serialize($array));
                wp_send_json_success();
            }
        }
    }

    public function update_license_data() {
        if (current_user_can('administrator')) {
            check_ajax_referer('schematic-nonce');

            $response = wp_remote_get($this->get_api_url('update_license_data', array('api_key' => get_option('_schematic_api_key'))), array(
                'sslverify' => false
            ));

            $res = json_decode($response['body'], true);

            if ($res) {
                if ($res['status']) {
                    $array = array('key' => trim(strip_tags($res['key'])), 'flag' => $this->to_bool($res['flag']));

                    update_option('_'.getPluginSlug().'_d_l', serialize($array));
                    wp_send_json_success($res);
                }
            }
        }

        wp_send_json_error($res);
    }

    public function verify_api_key($return = false, $key = null) {
        if (current_user_can('administrator')) {


            $_key = isset($_POST['_schematic_api_key']) ? $_POST['_schematic_api_key'] : get_option('_schematic_api_key');

            $response = wp_remote_get($this->get_api_url('validate_api_key', array('api_key' => $_key)), array(
                'sslverify' => false,
                'timeout' => 30
            ));

            if (is_object($response)) {
                return false;
            }

            $body = json_decode($response['body']);

            if (defined('DOING_AJAX') && DOING_AJAX) {
                // not a regular response - something happened
                if (!$body && $response['body']) {
                    wp_send_json_error($response['body']);
                }
                // not a regular response - something happened

                if ($return) {
                    return $body;
                }

                wp_send_json($body);
            } else {
                if ($response && $response['body']) {
                    $res = json_decode($response['body']);
                    return $res;
                }
            }
        }
    }

    public function get_plugin_update() {
        return $this->get_api_url('get_latest_plugin_version', array(
                    'api_key' => get_option('_schematic_api_key'),
        ));
    }

    public function post_params($array) {
        global $schematic_url;

        $params = array(
            'domain' => get_site_url(),
            'api_key' => get_option('_schematic_api_key'),
            'license_id' => get_option('_schematic_d_l'),
            'version' => get_option('_schematic_version'),
            'name' => 'WP SCHEMA PLUGIN',
            'path' => $schematic_url . basename($schematic_url));

        return array(
            'method' => 'POST',
            'timeout' => 30,
            'body' => array_merge($array, $params)
        );
    }

    public function get_api_post_url($action) {
        return $this->getUrl() . $action;
    }

    public function get_api_url($action, $array) {
        global $schematic_url, $schematic_file;

        $params = array(
            'domain' => get_site_url(),
            'version' => get_option('_schematic_version'),
            'name' => 'Schema',
            'path' => $schematic_url . basename($schematic_file),
        );

        $arr = array_merge($array, $params);
        $url = add_query_arg($arr, $this->getUrl() . $action);

        return $url;
    }

    public function schema_api_login($data) {
        $array = array(
            'data' => $data
        );

        $params = $this->post_params($array);
        $response = wp_remote_post($this->get_api_post_url('schema/api-login'), $params);

        return $this->getApiResponse($response);
    }

    public function schema_api_register($data) {
        $array = array(
            'data' => $data
        );

        $params = $this->post_params($array);
        $response = wp_remote_post($this->get_api_post_url('schema/api-register'), $params);

        return $this->getApiResponse($response);
    }

    public function schema_api_save_profile($data) {
        $array = array(
            'data' => $data
        );

        $params = $this->post_params($array);
        $response = wp_remote_post($this->get_api_post_url('schema/api-save-profile'), $params);

        return $this->getApiResponse($response);
    }

    public function schema_submit($data) {
        $array = array(
            'data' => serialize($data),
        );

        $params = $this->post_params($array);
        $response = wp_remote_post($this->get_api_post_url('schema/submit'), $params);

        return $this->getApiResponse($response);
    }

    public function schema_browse_database() {
        $array = array(
            'data' => serialize(getSchematicCatalogOptions()),
        );

        $params = $this->post_params($array);
        $response = wp_remote_post($this->get_api_post_url('schema/browse'), $params);

        return $this->getApiResponse($response);
    }

    protected function getApiResponse($response) {

        if ($response && isset($response['body'])) {
            $response = json_decode($response['body'], true);

            if ($response && isset($response['status']) && $response['status'] === 'error' && isset($response['note'])) {
                update_option('_'.getPluginSlug().'_d_l', serialize($response['note']));
            }


            return $response;
        }
    }

}

$schematicApi = new SchematicApi();
