<?php

namespace SiteZen\Telemetry\Connectors;


class Application
{
    public function __construct($parameters = [])
    {
    }

    public static function getUrl($path): string
    {
        $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")
            . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

        $url .= "/api/public/v1.0/sitezen/{$path}";
        return $url;
    }

    public static function apiRequest($config, $path, $headers = [], $data = null)
    {
        $curl = curl_init(self::getUrl($path));
        $headers[] = "X-TOKEN: {$config['token']}";
        $headers[] = "Accept: application/json";

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($curl);
        if ($response === false) {
            $result = [
                'error' => "cURL error: " . curl_error($curl)
            ];
        } else {
            $responseArray = json_decode($response, true);
            $result = $responseArray ?? ['unknown: ' . $response];
            $result['_api_request'] = $responseArray['_request'] ?? 'not set';
        }
        curl_close($curl);
        return $result;
    }

    public static function applicationData($config): array
    {
        return self::apiRequest($config, 'application');
    }

    public static function threatsUserData($config): array
    {
        return self::apiRequest($config, 'application/threats_users');
    }

    public static function cleanup($config, $request): array
    {
        // remove test accounts by email pattern
        $email_pattern = isset($request['email_pattern']) ? $request['email_pattern'] : '';

        $headers = ["X-EMAIL-PATTERN: " . $email_pattern];
        return [
            'result' => self::apiRequest($config, 'cleanup', $headers),
        ];
    }
}
