<?php

__RB_signedInOnly();

$inputRules = [
    "firstname" => ["required" => true, "validate" => ["regex" => REGEX_UNIVERSAL_NAME_NUMBER_EXTRA]],
    "lastname" => ["required" => true, "validate" => ["regex" => REGEX_UNIVERSAL_NAME_NUMBER_EXTRA]],
    "address" => ["required" => true, "validate" => ["regex" => REGEX_UNIVERSAL_NAME_NUMBER_EXTRA]],
    "city" => ["required" => true, "validate" => ["regex" => REGEX_UNIVERSAL_NAME_NUMBER_EXTRA]],
    "zipcode" => ["required" => true, "validate" => ["regex" => REGEX_UNIVERSAL_NAME_NUMBER_EXTRA]],
    "email" => ["required" => true, "validate" => ["custom" => 'validEmail']],
    "phone" => ["required" => true, "validate" => ["regex" => REGEX_PHONE_NUMBER_GENERAL]],
];

if (empty($_POST['firstname']) && isset($_POST['firstName'])) {
    $_POST['firstname'] = $_POST['firstName'];
}

if (empty($_POST['lastname']) && isset($_POST['lastName'])) {
    $_POST['lastname'] = $_POST['lastName'];
}

if (empty($_POST['email']) && isset($_POST['emailAddress'])) {
    $_POST['email'] = $_POST['emailAddress'];
}

if (empty($_POST['phone']) && isset($_POST['phoneNumber'])) {
    $_POST['phone'] = $_POST['phoneNumber'];
}

if (empty($_POST['zipcode']) && isset($_POST['postalCode'])) {
    $_POST['zipcode'] = $_POST['postalCode'];
}

if (!empty($_POST['email'])) {
    $_POST['email'] = preg_replace('/\s/', '', $_POST['email']);
    $_POST['email'] = str_replace(',', '.', $_POST['email']);
    $_POST['email'] = str_replace('..', '.', $_POST['email']);

    $_POST['email'] = explode('@', $_POST['email']);
    $_POST['email'][count($_POST['email']) - 1] = idn_to_ascii($_POST['email'][count($_POST['email']) - 1], IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);
    $_POST['email'] = implode('@', $_POST['email']);
}

if (!empty($_POST['phone'])) {
    $_POST['phone'] = preg_replace('/\s/', '', $_POST['phone']);
}

function validEmail($email) {
    if (!preg_match(REGEX_MAIL, $email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return false;
    }

    $email_host = array_slice(explode("@", $email), -1)[0];

    if (!filter_var($email_host, FILTER_VALIDATE_IP, [ 'flags' => FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ])) {
        if (!checkdnsrr($email_host . '.', "MX")) {
            return false;
        }
    }

    return true;
}

if (__RB_validateInput($inputRules, 'user_settings')) {
    // api
    $data = [
        'id' => $_SESSION['id'],
        'firstName' => $_POST['firstname'],
        'lastName' => $_POST['lastname'],
        'address' => $_POST['address'],
        'city' => $_POST['city'],
        'postalCode' => $_POST['zipcode'],
        'phoneNumber' => $_POST['phone'],
        'email' => $_POST['email']
    ];

    if (__RB_api_cloud(__RB_API_ACTION_CLOUD_CUSTOMER_UPDATE, $data, $json)) {
        $_SESSION['address']['first_name'] = $_POST['firstname'];
        $_SESSION['address']['last_name'] = $_POST['lastname'];
        $_SESSION['address']['address'] = $_POST['address'];
        $_SESSION['address']['postal_code'] = $_POST['zipcode'];
        $_SESSION['address']['city'] = $_POST['city'];
        $_SESSION['address']['phone'] = $_POST['phone'];
        $_SESSION['address']['email'] = $_POST['email'];

        $__RB_success['user_settings'] = true;

    } else {
        if ($json && is_array($json) && !empty($json['code'])) {
            switch ($json['code']) {
                case 102:
                    $errorMsg = $__RB_LNG['error']['form']['address_update']['email_exists'];

                    break;

                case 1002:
                    $errorMsg = $__RB_LNG['error']['form']['address_update']['disabled_user'];

                    break;
                
                default: $errorMsg = "Process error";
            }

            __RB_errorHandler('user_settings', $json['code'] <= 1 ? 'process' : 'user_settings', $json['code'] <= 1 ? 'Process error' : $errorMsg);

        } else {
            __RB_errorHandler('user_settings', 'process', 'Process error');
        }
    }
}
