<?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['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
    $enabled = 1;
    $queryemail = $mysqli->prepare("SELECT id, username, emailaddress, enabled FROM app_users WHERE username = ? AND enabled = ?");
    $queryemail->bind_param("si", $username, $enabled);
    $queryemail->execute();
    $emailfromdb = $queryemail->get_result()->fetch_assoc();
    $fetchedemailfromdb = $emailfromdb['emailaddress'];

    // 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
           $reg = 1;
           $enbld = 1;
           $entertokenquery = $mysqli->prepare("UPDATE app_users SET token = ? WHERE username = ? AND registered = ? AND enabled = ?");
           $entertokenquery->bind_param("ssii", $token, $username, $reg, $enbld);
           $entertokenquery->execute();

           // Create the verification email
           $verificationLink = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'] . "/src/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: ../login.php");
}

?>