<?php

/**
 * @copyright 2024 Double Bastion LLC <www.doublebastion.com>
 *
 * @author Double Bastion LLC
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

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 {
            $query0 = $mysqli->prepare("SELECT id, username, emailaddress FROM panelusers WHERE emailaddress=?");
            $query0->bind_param("s", $currentSentEmail);
            $query0->execute();
            $fetchres = $query0->get_result();
            $fetchData = $fetchres->fetch_row();
            $query0->close();

            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 panelusers SET password = '$newPassword', registered = '0', token = '$token', temporary = '$initPassword' WHERE id = '$userID'");

                // 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 = "RED SCARF Suite Panel 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>
                            RED SCARF Suite Panel<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
                                     panel 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: panel-login.php");
}

?>
