<?php
if(!defined('APPLICATION_VERSION')){
    die("Permission denied!");
}

if(isset($_POST['resetPassword']) && isset($_POST['newPassword']) && isset($_POST['confirmPassword'])){
    if(!empty($_POST['newPassword'] && !empty($_POST['confirmPassword']))) {
        $passwords = [
            'newPassword' => $_POST['newPassword'],
            'confirmPassword' => $_POST['confirmPassword']
        ];
        $confirmationData = $user->resetPassword(json_encode($passwords));
    } else {
        $confirmationData['messages'][] = [
            'code' => 'error',
            'message' => 'PASSWORDS_MISSING'
        ];
    }
}

?>

<div class="row">
    <div class="wiaas-title col-sm-12">
        <h1><?php echo APPLICATION_NAME;?></h1>
    </div>
</div>
<div class="row">
    <div class="col-sm-4 col-sm-offset-4">
        <form id="reset-password-form" action="" method="post" class="form-signin">
            <?php
                echo '<h2 class="form-signin-heading">{{ "validation.headers.RESET_TITLE" | translate }} - <b>'.$user->getSetPasswordUsername().'</b></h2>';
            ?>
            <div class="alert alert-info">
                <span class="glyphicon glyphicon-info-sign"></span>
                {{'validation.messages.PASSWORD_CHARACTERS' | translate}}
            </div>
            <label for="passwd" class="sr-only">{{ 'validation.headers.NEW_PASSWORD' | translate }}</label>
            <input id="new-passwd" name="newPassword" type="password" class="form-control" placeholder="{{ 'validation.headers.NEW_PASSWORD' | translate }}" required autofocus />
            <label for="confirmPasswd" class="sr-only">{{ 'validation.headers.CONFIRM_PASSWORD' | translate }}</label>
            <input id="confirm-passwd" name="confirmPassword" type="password" class="form-control" placeholder="{{ 'validation.headers.CONFIRM_PASSWORD' | translate }}" required />
            <button id="reset-password-button" type="submit" name="resetPassword" class="btn btn-lg btn-primary btn-block">{{ 'validation.buttons.SET_PASSWORD' | translate }}</button>
        </form>
        <?php
            if(isset($confirmationData) && $confirmationData['messages']) {
                foreach($confirmationData['messages'] as $position => $messageData) {
                    if($messageData['code'] === 'success' && $messageData['message'] === 'PASSWORD_GENERATED') {
                        header('Location:login?message='.$messageData['message']);
                    } else {
                        echo '<div id="confirmation-message-'.$position.'" class="password-confirmation-messages alert alert-danger">';
                            echo '<span class="glyphicon glyphicon-alert"></span> {{"validation.messages.'.$messageData['message'].'" | translate}}';
                        echo '</div>';
                    }
                }
            }
         ?>
    </div>
</div>
