<?php

/*
 *
 *
 * provide api to cloudbeez server to set API Key
 *
 *
 */


class cloudBeezApiProvider
{

    public function __construct()
    {
        if (!$this->checkApiKey($_POST['api_key'])) {
            mh_exit();
        }
    }

    function cloudBeezApiProvider()
    {
        self::__construct();
    }


    public function run()
    {
        if ($_POST['cldbz'] == 'set_api_key') {
            // set api_key
            $api_key = $_POST['data']['cloudbeez_api_key'];

            mh_insert_config_value(array(
                'configuration_key' => 'CLOUDLOADER_API_KEY',
                'configuration_value' => $api_key
            ), true);
            $this->sentResponse(array('result' => true, 'value' => $api_key));
        }
    }

    public function testConnection()
    {
        $data = array('result' => true);
        $this->sentResponse($data);
    }

    public function checkApiKey($api_key)
    {
        return ($api_key == mh_cfg('CLOUDLOADER_PRIVATE_API_KEY'));
    }


    function sentResponse($data)
    {
        echo $this->handleRequest($data);
        mh_exit();
    }

    function handleRequest($data)
    {
        if (version_compare(PHP_VERSION, "5.3", ">=")) {
            $json = json_encode($data, true); // 2n parameter options not used???
        } else {
            $json = json_encode($data);
        }
        return $json;
    }

}
