<?php

/**
 * Logintap class file.
 * @author Pavel Svinarev <pavel@mobsted.com>
 * @copyright Copyright 2014-2020 Logintap.com
 * @license https://www.gnu.org/licenses/gpl-2.0.html
 * @package logintap
 */

/**
 * Class Logintap
 */
class Logintap
{
    /**
     * @var string
     */
    private $_tenant;

    /**
     * @var string
     */
    private $_login;

    /**
     * @var string
     */
    private $_password;

    /**
     * @var string
     */
    private $_host;

    /**
     * @var string
     */
    private $_url;

    /**
     * @var null
     */
    private $_devMode;

    /**
     * @var null
     */
    private $_appUUID;

    /**
     * Logintap constructor.
     * @param string $tenant
     * @param string $appUUID
     * @param string $login
     * @param string $password
     * @param $devMode
     */
    public function __construct($tenant, $appUUID, $login, $password, $devMode = null)
    {
        $this->_tenant = $tenant;
        $this->_appUUID = $appUUID;
        $this->_host = 'logintap.com';
        $this->_url = 'https://' . $this->_tenant . '-admin.' . $this->_host . '/api/v8/';
        $this->_login = $login;
        $this->_password = $password;
        $this->_devMode = $devMode;

        if (isset($this->_devMode) && $this->_devMode) {
            $this->_url = $this->_tenant;
        }
    }

    /**
     * The private function to send api request to Logintap platform
     * @param array $params
     * @return array
     */
    private function sendRequest($params)
    {
        $type = isset($params['type']) ? $params['type'] : 'GET';
        $method = isset($params['method']) ? $params['method'] : '';
        $headers = isset($params['headers']) ? $params['headers'] : [];
        $data = isset($params['data']) ? $params['data'] : [];

        $jsonType = false;

        $url = $this->_url . $method;

        if ($type == 'GET') {
            $url .= '?' . http_build_query($data);
        }

        foreach($headers as $index => $header) {
            if (strpos($header, 'application/json') !== false) {
                $jsonType = true;
                break;
            }
        }

        $c = curl_init($url);

        curl_setopt($c, CURLOPT_HTTPHEADER, $headers);

        if ($type == 'POST') {
            curl_setopt($c, CURLOPT_POST, 1);
            if ($jsonType) {
                curl_setopt($c, CURLOPT_POSTFIELDS, json_encode($data));
            } else {
                curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($data));
            }
        }

        if ($type == 'DELETE') {
            curl_setopt($c, CURLOPT_CUSTOMREQUEST, "DELETE");
        }

        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);

        $server_output = curl_exec($c);
        $server_code = curl_getinfo($c, CURLINFO_RESPONSE_CODE);

        curl_close($c);

        return [
            'code' => $server_code,
            'output' => $server_output
        ];
    }

    /**
     * Function to call the API method to get access and refresh tokens for all further requests
     * @return array
     */
    public function getUserTokens()
    {
        return $this->sendRequest([
            'type' => 'GET',
            'method' => 'auth',
            'headers' => [],
            'data' => [
                'login' => $this->_login,
                'password' => $this->_password,
            ],
        ]);
    }

    /**
     * Function calling the API method to create a new user/object for mobile auth
     * @param string $token
     * @param array $params
     * @return array
     */
    public function createObject($token, $params)
    {
        $params['ApplicationUUID'] = $this->_appUUID;
        $params['Enabled'] = 1;

        return $this->sendRequest([
            'type' => 'POST',
            'method' => 'object',
            'headers' => [
                'Authorization: Bearer ' . $token
            ],
            'data' => $params,
        ]);
    }

    /**
     * Function calling the API method to request a mobile auth for existing user/object
     * @param string $token
     * @param array $params - example
     * ['objectUUID' => '7a503b27-8d25-40da-910d-c56cd35108bf', 'appUUID' => '55b5094e-05a0-43df-8663-4f1a0b8bbf65']
     * @return array
     */
    public function loginRequest($token, $params)
    {
        return $this->sendRequest([
            'type' => 'POST',
            'method' => 'logintap/loginrequest',
            'headers' => [
                'Authorization: Bearer ' . $token
            ],
            'data' => $params,
        ]);
    }

    /**
     * Function calling the API method to create all bot links for object
     * @param string $token
     * @param array $params - example ['objectUUID' => '7a503b27-8d25-40da-910d-c56cd35108bf']
     * @return array
     */
    public function createBotLinks($token, $params)
    {
        return $this->sendRequest([
            'type' => 'POST',
            'method' => 'refsbots/add',
            'headers' => [
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json',
            ],
            'data' => $params,
        ]);
    }

}