<?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['vd_ajax_call']) && ($_POST['vd_ajax_call'] == $_SESSION['validate_access'])) {

define('ACCESSCONST', TRUE);

require('db-connect.php');

  if (isset($_POST['emailaddress']) && isset($_POST['login']) && isset($_POST['password']) && isset($_POST['selectrole']) && isset($_POST['currentmessage'])) {

     $currentuseremail = $_POST['emailaddress'];
     $currentusername = $_POST['login'];
     $currentuserpswd = password_hash($_POST['password'], PASSWORD_DEFAULT);
     $currentuserrole = $_POST['selectrole'];

     $currentmessage = $_POST['currentmessage'];

     if ($currentmessage == '' && $currentuseremail != '' && $currentusername != '' && $currentuserpswd != '' && $currentuserrole != '') {

            // Check if there is any other user with the same username or email
            $query0 = $mysqli->query("SELECT username, emailaddress FROM panelusers");

            $duplicatename = 0;
            $duplicateemail = 0;

            while ($row = $query0->fetch_row()) {

                   if ($currentusername == $row[0]) {
                       $duplicatename = 1;
                   }

                   if ($currentuseremail == $row[1]) {
                       $duplicateemail = 1;
                   }
            }

            if ($duplicatename == 1 && $duplicateemail == 0) {
                $result = 'failure';
                $messageoninsert = "Your username is already in use. Please choose a different username !";
            } elseif ($duplicatename == 0 && $duplicateemail == 1) {
                $result = 'failure';
                $messageoninsert = "Your email address is already in use. Please choose a different email address !";
            } elseif ($duplicatename == 1 && $duplicateemail == 1) {
                $result = 'failure';
                $messageoninsert = "Your username and email address are already in use. Please choose a different username and email address !";
            } 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(50);
                $verificationLink = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'] . "/verification.php?key=" . $token;
                $domaininit = explode(".", $_SERVER['HTTP_HOST']);
                array_shift($domaininit);
                $domain = implode(".", $domaininit);

                // Mention the content-type, because it's an HTML email
                $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>
                            Thank you for signing up to RED SCARF Suite Panel. To complete the registration process, please click 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>
                            Thank you,<br>
                            RED SCARF Suite Panel<br>
                            Host: '" . $_SERVER['HTTP_HOST'] . "'";

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

                try {

                   // Insert the email, username, password and user role in the 'panelusers' table
                   $registered = '0';
                   $temporary = '';
                   $enabled = 1;
                   $query1 = $mysqli->prepare("INSERT INTO panelusers (userrole, username, password, emailaddress, registered, token, temporary, enabled) VALUES (?, ?, ?, ?, ?,
                                               ?, ?, ?)");
                   $query1->bind_param("sssssssi", $currentuserrole, $currentusername, $currentuserpswd, $currentuseremail, $registered, $token, $temporary, $enabled);
                   $query1->execute();
                   $query1->close();

                   $result = 'success';
                   $messageoninsert = "A message has been sent to your email address ! Please follow the instructions in the received email to complete the registration process !";

                } catch(mysqli_sql_exception $e) {
                        $result = 'failure';
                        $messageoninsert = "An error occurred while saving your data.";
                  }
            }

            $response = array('result' => $result, 'messageoninsert' => $messageoninsert);
            echo json_encode($response);
     }
  }

} else {

     header("Location: panel-login.php");
}

?>