<?php

$text = $languageForm['changeAddress'];

$error['changeAddress']['form'] = [];
$user['address'] = [
    "firstName" => $_SESSION['address']['first_name'],
    "lastName" => $_SESSION['address']['last_name'],
    "address" => $_SESSION['address']['address'],
    "postalCode" => $_SESSION['address']['postal_code'],
    "city" => $_SESSION['address']['city'],
    "phoneNumber" => $_SESSION['address']['phone']
];

do {
    if (isset($_POST) && isset($_POST['submitChangeAddress'])) {
        $rules = [
            'firstName' => [ "regex" => REGEX_UNIVERSAL_NAME_EXTRA ],
            'lastName' => [ "regex" => REGEX_UNIVERSAL_NAME_EXTRA ],
            'address' => [ "regex" => REGEX_UNIVERSAL_NAME_NUMBER_EXTRA ],
            'postalCode' => [ "regex" => REGEX_POSTAL_CODE_GENERAL ],
            'city' => [ "regex" => REGEX_UNIVERSAL_NAME_EXTRA ],
            'phoneNumber' => [ "regex" => REGEX_PHONE_NUMBER_GENERAL ],
        ];

        $data = ['id' => $_SESSION['id']];

        foreach ($rules as $field => $rule) {
            if (!isset($_POST[$field])) {
                $error['changeAddress']['form'][$field][] = $languageStd['missing'] . $languageValidation[$field]['name'];
            } else {
                $input = $_POST[$field];

                if (empty($input)) {
                    $error['changeAddress']['form'][$field][] = $languageValidation[$field]['name'] . $languageStd['empty'];
                }

                if (isset($rule['regex']) && !preg_match($rule['regex'], $input)) {
                    $error['changeAddress']['form'][$field][] = $languageValidation[$field]['validation'];
                }
            }

            if (!isset($error['changeAddress']['form'][$field])) {
                $data[$field] = $input;
            }
        }

        if (count($error['changeAddress']['form'])) {
            break;
        }

        $json = "";

        if (api(API_REQ_CHANGE_ADDRESS, $data, $json)) {
            $_SESSION['address'] = $json['address'];

            $success['changeAddress'][] = $languageSuccess['changeAddress']['changed'];

            break;
        }

        $error['changeAddress']['form']['default'][] = $languageError['changeAddress']['default'];
    }
} while (0);
