<?php

// minimal script
use Adldap\Query\Operator;
use Sift\DotEnv;
use SoWa\Ldap\ConnectionFactory;
use SoWa\Ldap\OrganizationUnitNames;
use SoWa\Ldap\Util\ValidatePasswordStrengthFunction;

require_once __DIR__ . '/../../vendor/autoload.php';

// error_reporting(E_ALL);
// ini_set('display_errors', true);

\error_reporting(0);
\ini_set('display_errors', false);

$errors = [];
$login = null;
$updated = false;

if ('POST' == $_SERVER['REQUEST_METHOD']) {
    $login = $_POST['login'];
    $oldPassword = \trim($_POST['old_password']);
    $newPassword = \trim($_POST['new_password']);
    $newPasswordConfirmation = \trim($_POST['new_password2']);
    if (empty($login)) {
        $errors[] = 'Your login is empty';
    }
    if (empty($oldPassword)) {
        $errors[] = 'Old password is empty';
    }
    if (empty($newPassword) || empty($newPasswordConfirmation)) {
        $errors[] = 'New password or password confirmation is empty';
    } else {
        if ($newPassword !== $newPasswordConfirmation) {
            $errors[] = 'The confirmation passwords are not the same';
        }
        // validate the password strength!
        try {
            (new ValidatePasswordStrengthFunction())($newPassword);
        } catch (\InvalidArgumentException $e) {
            $errors[] = \sprintf('New password is not valid. %s', $e->getMessage());
        }
    }

    // let's do it!
    if (empty($errors)) {
        // load environment variables
        DotEnv::load(__DIR__ . '/../../');

        $conn = ConnectionFactory::getConnection();
        $provider = $conn->getDefaultProvider();
        try {
            $config = $provider->getConfiguration();
            $baseDn = $config->get('base_dn');
            $username = \sprintf('uid=%s,ou=%s,%s', $login, OrganizationUnitNames::PEOPLE, $baseDn);

            // try to bind with the credentials, so we known that the password is valid
            $conn->connect(null, $username, $oldPassword);

            // bind with admin rights
            $conn->connect();

            $search = $provider->search();

            $users = $search->users()->where(
                'uid', Operator::$equals, $login
            )->get();

            if (!\count($users)) {
                throw new \InvalidArgumentException();
            }

            $user = $users->get(0);

            $user->setPassword($newPassword);
            $result = $user->save();

            $login = null;
            $updated = true;
        } catch (\Adldap\Auth\BindException $e) {
            $errors[] = 'The user was not found or invalid password given.';
        } catch (\InvalidArgumentException $e) {
            $errors[] = 'The user was not found or invalid password given.';
        } catch (\Exception $e) {
            $errors[] = 'The user was not found or invalid password given.'; // something unknown happened
        }
    }
}

?>
<html>
<head>
    <title>Account ~ SoWa</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <style>

        body {
            border-top: 0.5em solid #f25e3b;
        }

        .main {
            margin: 0 auto;
            max-width: 800px;
            padding: 2em;
        }

        .main__form {
            max-width: 30em;
            margin: 0 auto;
        }

        .main__heading {
            text-align: center;
            background: #43515b;
        }

    </style>
    <script src="js/sha1-min.js"></script>
    <script src="js/xkcd_pw.js.php"></script>
</head>
<body>

<header class="main__heading">
    <a href=""><img src="account.png" title="SoWa Research Infrastructure"/></a>
</header>
<div class="container main">


    <form action="" method="post" class="main__form">

        <h3>Change your password</h3>
        <hr>

        <fieldset>
            <?php if ($updated) { ?>
                <div class="alert alert-success" role="alert">
                    <h4 class="alert-heading">
                        Success!
                    </h4>
                    Your password has been updated.
                </div>
            <?php } ?>

            <?php if (\count($errors)) { ?>
                <div class="alert alert-danger" role="alert">
                    <h4 class="alert-heading">
                        There are errors in the form. Please correct them and submit again.
                    </h4>
                    <ul class="form-errors">
                        <?php foreach ($errors as $error) { ?>
                            <li><?php echo $error; ?></li>
                        <?php } ?>
                    </ul>
                </div>
            <?php } ?>
            <div class="form-group">
                <label for="login">Your login</label>
                <input name="login" value="<?php echo \htmlspecialchars($login); ?>" type="text" class="form-control"
                       id="login" placeholder="Enter your login">
            </div>
            <div class="form-group">
                <label for="InputPassword1">Old password</label>
                <input type="password" name="old_password" class="form-control" id="InputPassword1"
                       placeholder="Your old password">
            </div>

            <div class="form-group">
                <label for="InputPassword2">New password</label>
                <input type="password" name="new_password" class="form-control" aria-describedby="passwordHelp"
                       id="InputPassword2"
                       placeholder="Enter new password">
                <small id="passwordHelp" class="form-text text-muted">Your password must be at least 12 characters
                    long.
                </small>
            </div>

            <div class="form-group">
                <label for="InputPassword3">Confirm new password</label>
                <input type="password" name="new_password2" class="form-control" id="InputPassword3"
                       placeholder="Confirm new password">
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-primary">Update password</button>
            </div>

            <div class="alert alert-success" role="alert">
                <h4>Random password generator</h4>
                <div class="xkcd_panel">
                    <pre id="xkcd_pw_gen_result"></pre>
                    <input class="btn small secondary" type="button" value="Generate random password" onclick="xkcd_pw_gen()" />
                    <hr>
                </div>
                <small>We recommend adding another word, changing it slightly, or altering it with special characters. <a href="https://xkcd.com/936/">Why?</a></small>
            </div>

        </fieldset>
</div>
</body>
</html>
