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

 define('ACCESSCONST', TRUE);

 require('db-connect.php');

    $username = $_POST['username'];
    $currentEmail = $_POST['current_email'];
    $newEmail = $_POST['new_email'];

    // Get the email address of the current user from the 'app_users' table
    $queryemail = $mysqli->query("SELECT id, username, emailaddress, enabled FROM app_users WHERE username = '$username' AND enabled = 1");
    $emailfromdb = $queryemail->fetch_row();
    $fetchedemailfromdb = $emailfromdb[2];

    // Check if there is any other user with the same email address as the new email address
    $getemails = $mysqli->query("SELECT emailaddress FROM app_users");

    $duplicateemail = 0;

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

           if ($newEmail == $row[0]) {
               $duplicateemail = 1;
               break;
           }
    }


    if ($fetchedemailfromdb == $currentEmail) {

       if ($duplicateemail == 0) {

           /**
            *  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);

           // Enter the new token in the database
           $entertokenquery = $mysqli->query("UPDATE app_users SET token = '$token' WHERE username = '$username' AND registered = 1 AND enabled = 1");

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

           $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 email address change request. To change your current Roundpin email address, please verify your address by clicking 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>
                       After email address verification, your new email address will be assigned to your Roundpin account and saved to the database.<br><br>
                       Thank you,<br>
                       Roundpin<br>
                       Host: '" . $_SERVER['HTTP_HOST'] . "'";

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

           $emailchangemessage = "An email has been sent to your new email address. Please click on the link included in the received email to change your Roundpin user email address.";

       } else { $emailchangemessage = "The new email address is already used by another Roundpin user. Please, choose a different email address!"; }
        
    } else { $emailchangemessage = "The email address you have entered in the 'Current Email' field doesn't match your current email address!"; }

    echo json_encode($emailchangemessage);

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

?>