<?php

/* информация об переменах */
function authorizationInformation() {
    global $_SESSION;
    return ['login' => $_SESSION['Login'] == 'true' ? 'true' : 'false'];
}

function registrationRequest() {
    global $path, $config;
    $exists = false;
    $requestFile = simplexml_load_file($path . $config['usersRequest']);
    foreach ($requestFile->users->user as $child) {
        if ((string)$child['name'] === $_POST['login']) {
            $exists = true;
            break;
        }
    }
    $usersFile = simplexml_load_file($path . $config['users']);
    foreach ($usersFile->users->user as $child) {
        if ((string)$child['name'] === $_POST['login']) {
            $exists = true;
            break;
        }
    }

    $email = $_POST['email'];
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return ['status' => 'incorrect mail'];
    }
    $domain = substr(strrchr($email, "@"), 1);
    if (!checkdnsrr($domain, "MX")) {
        return ['status' => 'incorrect mail'];
    }

    if ($exists) {
        return ['status' => 'name coincidence'];
    }

    $requestFile = simplexml_load_file($path . $config['usersRequest']);
    $requestFilePath = $path . $config['usersRequest'];

    $newUser = $requestFile->users->addChild('user');
    $newUser->addAttribute('name', $_POST['login']);
    $newUser->addAttribute('pass', $_POST['pass']);
    $newUser->addAttribute('access', '');
    $newUser->addAttribute('email', $_POST['email']);
    $newUser->addAttribute('link', md5($_POST['login'].$_POST['pass']));

    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($requestFile->asXML());

    if ($dom->save($requestFilePath)) {
        return registrationRequestMail();
    } else {
        return ['status' => 'error while creating'];
    }
}

function registrationRequestMail() {
    global $config;

    $to = $config['emailAdmin'];
    $subject = '=?UTF-8?B?'.base64_encode('Запрос на создание аккаунта на сайте ').'?='. $_SERVER['HTTP_HOST'];
    $message = 'Логин: ' . $_POST['login'] . "\r\n";
    $message .= 'Пароль: ' . $_POST['pass'] . "\r\n";
    $message .= 'Почта: ' . $_POST['email'] . "\r\n";
    $message .= 'Сайт: ' . $config['server'] . "\r\n";
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From: info@oblat.lv";

    if (mail($to, $subject, $message, $headers)) {
        return ['status' => true];
    } else {
        return ['status' => false, 'error' => 'Ошибка при отправке письма.'];
    }
}
?>