<?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();
 // header('Set-Cookie: PHPSESSID= ' . session_id() . '; SameSite=strict; Secure=true; HttpOnly=true;');

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 app_users");

            $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'] . "/src/email-address-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 = "Roundpin email address verification";

                $message = "Hello, <br><br>
                            Thank you for signing up to Roundpin. To complete the registration process, please click on the link from 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>
                            Roundpin<br>
                            Host: '" . $_SERVER['HTTP_HOST'] . "'";

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

                try {

                   // Insert the data entered in the sign up form in the 'app_users' table
                   $registered = "0";
                   $temporary = "";
                   $enabled = 1;
                   $crTime = date("Y-m-d H:i:s");
                   $query1 = $mysqli->prepare("INSERT INTO app_users (userrole, username, password, emailaddress, registered, token, temporarypass, date_added, enabled) VALUES
                                               (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                   $query1->bind_param("ssssssssi", $currentuserrole, $currentusername, $currentuserpswd, $currentuseremail, $registered, $token, $temporary, $crTime, $enabled);
                   $query1->execute();

                   $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: ../login.php");
}

?>
