<?php

$text = $languageForm['changePassword'];

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

// TODO: Lock account after 3 incorrect password attempts

do {
    if (isset($_POST) && isset($_POST['oldPassword']) && isset($_POST['newPassword']) && isset($_POST['newPasswordRepeat'])) {
        if (empty($_POST['oldPassword'])) {
            $error['changePassword']['form']['oldPassword'][] = $languageValidation['oldPassword']['name'] . $languageStd['empty'];
        }

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

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

        if ($_POST['newPassword'] != $_POST['newPasswordRepeat']) {
            $error['changePassword']['form']['newPasswordRepeat'] = [];
            $error['changePassword']['form']['didntMatch'][] = $languageError['changePassword']['didntMatch'];
        }

        if ($_POST['newPassword'] == $_POST['oldPassword']) {
            $error['changePassword']['form']['newPassword'] = [];
            $error['changePassword']['form']['newPasswordRepeat'] = [];
            $error['changePassword']['form']['oldNewSame'][] = $languageError['changePassword']['oldNewSame'];
        }

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

        $data = [
            'id' => $_SESSION['id'],
            'oldPassword' => $_POST['oldPassword'],
            'newPassword' => $_POST['newPassword']
        ];

        $json = "";

        if (api(API_REQ_CHANGE_PASSWORD, $data, $json)) {
            $success['changePassword'][] = $languageSuccess['changePassword']['changed'];

            break;
        }

        $error['changePassword']['form']['oldWrong'][] = $languageError['changePassword']['oldWrong'];
    }
} while (0);
