<?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;

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

    /**
     * Logintap constructor.
     * @param string $tenant
     * @param string $appUUID
     * @param string $login
     * @param string $password
     * @param $devMode
     */
    public function __construct(string $tenant, string $appUUID, string $login, string $password, $devMode = null)
    {
        $this->_host = 'logintap.com';
        $this->_tenant = $tenant;
        $this->_appUUID = $appUUID;
        $this->_host = 'logintap.com';
        $this->_url = 'https://' . $this->_tenant . '-admin.' . $this->_host . '/api/v1/';
        $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(array $params): array
    {
        $type = $params['type'] ?? 'GET';
        $method = $params['method'] ?? '';
        $headers = $params['headers'] ?? [];
        $data = $params['data'] ?? [];

        $jsonType = $params['data']['json_raw'] ?? false;

        if (isset($params['data']['json_raw'])) {
            unset($params['data']['json_raw']);
        }

        $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 getUserToken(): array
    {
        return $this->sendRequest([
            'type' => 'POST',
            'method' => 'auth_oauth',
            'headers' => [],
            'data' => [
                'applicationUUID' => $this->_appUUID,
            ],
        ]);
    }

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

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

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



}