<?php

// this function has access to dashboard_encryption_key constant.
// add here the format of string after decrepted
// keep return format array indexes intact
function srm_decrept_connectionstring($encrypted_connection_string)
{
    $connection_string = decrypt_native($encrypted_connection_string);
    $connection_string = parse_connection_string($connection_string);

    return array(
        column_connection_user      => $connection_string["user"],
        column_connection_pass      => $connection_string["password"],
        column_connection_charset   => $connection_string["charset"],
        column_connection_collation => $connection_string["collation"],
        column_connection_port      => $connection_string["port"]
    );
}

function parse_connection_string($input)
{
    $pairs  = explode(';', $input);
    $result = [];

    foreach ($pairs as $pair) {
        list($key, $value) = explode('=', $pair, 2);
        $result[$key]      = $value;
    }

    return $result;
}

function decrypt_native($payload)
{
    $key = dashboard_encryption_key;
    $key = base64_decode(explode("base64:", $key)[1]);

    $cipher = 'aes-256-cbc';

    $payload = get_json_payload_native($payload);

    $iv = base64_decode($payload['iv']);

// Here we will decrypt the value. If we are able to successfully decrypt it

// we will then unserialize it and return it out to the caller. If we are
    // unable to decrypt this value we will throw out an exception message.
    $decrypted = \openssl_decrypt(
        $payload['value'],
        strtolower($cipher),
        $key,
        0,
        $iv,
        $tag ?? ''
    );

    if ($decrypted === false) {
        throw new \Exception('Could not decrypt the data.');
    }

    return unserialize($decrypted);
}

function get_json_payload_native($payload)
{
    $payload = json_decode(base64_decode($payload), true);
    $cipher  = 'aes-256-cbc';

// If the payload is not valid JSON or does not have the proper keys set we will

// assume it is invalid and bail out of the routine since we will not be able

// to decrypt the given value. We'll also check the MAC for this encryption.
    if (!valid_payload_native($payload)) {
        throw new \Exception('The payload is invalid.');
    }

    if (!valid_mac_native($payload)) {
        throw new \Exception('The MAC is invalid.');
    }

    return $payload;
}

function valid_payload_native($payload)
{
    $cipher = 'aes-256-cbc';

    if (!is_array($payload)) {
        return false;
    }

    foreach (['iv', 'value', 'mac'] as $item) {
        if (!isset($payload[$item]) || !is_string($payload[$item])) {
            return false;
        }

    }

    if (isset($payload['tag']) && !is_string($payload['tag'])) {
        return false;
    }

    return strlen(base64_decode($payload['iv'], true)) === openssl_cipher_iv_length(strtolower($cipher));
}

function valid_mac_native(array $payload)
{
    return hash_equals(
        hash_native($payload['iv'], $payload['value']),
        $payload['mac']
    );
}

function hash_native($iv, $value)
{
    $key = dashboard_encryption_key;
    $key = base64_decode(explode("base64:", $key)[1]);

    return hash_hmac('sha256', $iv . $value, $key);
}

function base_path_native($path)
{
    return "../../../" . $path;
}

function config_native($path)
{
    $file_name = explode('.', $path)[0];

    if (file_exists('../../../dashboard/config/' . $file_name . ".php")) {
        $data = require base_path_native('dashboard/config/' . $file_name . ".php");
    } else {
        return false;
    }

    $paths = array_slice(explode('.', $path), 1);

    $result = $data;
    foreach ($paths as $path) {
        $result = $result[$path];
    }

    return $result;
}

function srm_login_url()
{
    $redirect = config_native("srm_config.installer.redirect");

    if (strpos($_SERVER["PHP_SELF"], "public") !== false) {
        return get_protocol() . $_SERVER["HTTP_HOST"] . explode(
            "/" . "public/",
            $_SERVER["PHP_SELF"]
        )[0] . $redirect;
    } else {
        return get_protocol() . $_SERVER["HTTP_HOST"] . "$redirect";
    }

}

function get_protocol()
{
    if (
        isset($_SERVER['HTTPS']) &&
        ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
        isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
        $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
    ) {
        $protocol = 'https://';
    } else {
        $protocol = 'http://';
    }

    return $protocol;
}

// function getLogoPath()

// {

//     $dashboard_connection = new DatabaseHandler(DEFAULT_HOST, DEFAULT_DBUSER, DEFAULT_DBPASS, DEFAULT_DBNAME);

//     $dbReader             = new Reader(tables_prefix . table_settings, $dashboard_connection);

//     $systemLogo = $dbReader->filter_by_column('settings_key', 'system_logo')[0]['settings_value'];

//     $path = explode("public/srm_modules", $_SERVER["PHP_SELF"])[0];

// // var_dump($path);

// // var_dump(file_exists($path . 'srm_storage/' . $systemLogo));

// // die;

//     if (file_exists($path . 'srm_storage/' . $systemLogo)) {

//         return $path . 'srm_storage/' . $systemLogo;

//     } else {

//         return $path . $systemLogo;

//     }

// }