<?php

$textForm = $languageForm['login'];

$error['login']['form'] = [];

// TODO: Lock account after 3 failed user-login attempts

do {
    if (isset($_POST) && isset($_POST['emailAddress']) && isset($_POST['password'])) {
        if (empty($_POST['emailAddress'])) {
            $error['login']['form']['emailAddress'][] = $languageValidation['emailAddress']['name'] . $languageStd['empty'];
        }

        if (!filter_var($_POST['emailAddress'], FILTER_VALIDATE_EMAIL)) {
            $error['login']['form']['emailAddress'][] = $languageValidation['emailAddress']['validation'];
        }

        if (empty($_POST['password'])) {
            $error['login']['form']['password'][] = $languageValidation['password']['name'] . $languageStd['empty'];
        }

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

        $data = [
            "emailAddress" => $_POST['emailAddress'],
            "password" => $_POST['password']
        ];

        $json = "";

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

            if ($_SESSION['lng'] === $_GET['lng']) {
                header("location: ../");
            } else {
                header("location: ../{$_SESSION['lng']}/");
            }

            exit;
        }
		
		//var_dump($json);
		
		if (isset($json['code']) && $json['code'] == 2) {
			$error['login']['form']['notActive'][] = $languageError['login']['notActive'];

		} else {
			$error['login']['form']['wrongLogin'][] = $languageError['login']['wrongLogin'];
		}
		
		$error['login']['form']['emailAddress'] = [];
		$error['login']['form']['password'] = [];
    }
} while (0);
