<?php
/**
 *  Copyright (C) 2021  Double Bastion LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the "LICENSE.txt" file located in the root directory.
 */

session_start();

if (isset($_POST['verifyToken']) && ($_POST['verifyToken'] == $_SESSION['forgotpass_access'])) {

define('ACCESSCONST', TRUE);

require('db-connect.php');

   $currentSentEmail = $_POST['emailforgot'];
   $currentMessage = $_POST['messageToUser'];

   if (($currentSentEmail != '') && ($currentMessage == '')) {

        // Search the database for the specified email
        try {
            $enabled = 1;
            $query0 = $mysqli->prepare("SELECT id, username, emailaddress, enabled FROM app_users WHERE emailaddress=? and enabled=?");
            $query0->bind_param("si", $currentSentEmail, $enabled);
            $query0->execute();
            $fetchres = $query0->get_result();
            $fetchData = $fetchres->fetch_row();

            if (empty($fetchData)) {

                $result = 'failure';
                $messageonrequest = "Your email address hasn't been found !";

            } else {

                /**
                 *  Send the verification email
                 */

                // Generate a random string to be used as the termination of the verification link
                function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
                         $pieces = [];
                         $max = mb_strlen($keyspace, '8bit') - 1;

                         for ($i = 0; $i < $length; ++$i) {
                              $pieces []= $keyspace[random_int(0, $max)];
                         }
                         return implode('', $pieces);
                }

                $token = random_str(55);

                // Update the appropriate fields for the user having the given email address
                $initPassword = random_str(14);
                $newPassword = password_hash($initPassword, PASSWORD_DEFAULT);

                $userID = $fetchData[0];

                $query1 = $mysqli->query("UPDATE app_users SET password = '$newPassword', registered = '0', token = '$token', temporarypass = '$initPassword' WHERE id = '$userID'
                                          AND enabled = 1");

                // Create the verification email
                $verificationLink = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'] . "/forgotpass-verification.php?token=" . $token;

                $domaininit = explode(".", $_SERVER['HTTP_HOST']);
                array_shift($domaininit);
                $domain = implode(".", $domaininit);

                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";

                $headers .= "From: " . "no-reply@" . $domain . "\r\n";

                $subject = "Roundpin email address verification";

                $message = "Hello, <br><br>
                            We have received your request related to regaining access to your account. Please verify your email address by clicking on
                            the link below: <br><br>
                            <a href='".$verificationLink."'>".$verificationLink."</a><br><br>
                            Alternatively, you can copy the link and paste it in the address bar of your browser.<br><br>
                            After email address verification you will receive a new email with further instructions.<br><br>
                            Thank you,<br>
                            Roundpin<br>
                            Host: '" . $_SERVER['HTTP_HOST'] . "'";

                // Send the email
                mail($currentSentEmail, $subject, $message, $headers);

                $result = 'success';
                $messageonrequest = "An email has been sent to your email address. Please follow the instructions in the received email to regain access to your
                                     Roundpin account.";
            }

        } catch (mysqli_sql_exception $e) {
                $result = 'failure';
                $messageonrequest = "An error occurred while processing your request. You can try sending your request again after a few moments !";
        }

        $reqresponse = array('result' => $result, 'messageonrequest' => $messageonrequest);
        echo json_encode($reqresponse);
   }

} else {
     header("Location: roundpin-login.php");
}

?>
