<?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.
 */

$retrievedToken = $_GET['token'];

if (($retrievedToken != '') && (strlen($retrievedToken) == 55)) {

  define('ACCESSCONST', TRUE);

  require('db-connect.php');

    // Find the user who has a token identical with the one retrieved from the link that has been clicked
    $registered = 0;
    $enabled = 1;
    $query0 = $mysqli->prepare("SELECT id, username, emailaddress, registered, token, temporarypass, enabled FROM app_users WHERE registered=? AND token=? AND enabled=?");
    $query0->bind_param("isi", $registered, $retrievedToken, $enabled);
    $query0->execute();
    $fetchedrow = $query0->get_result()->fetch_assoc();

    if (!$fetchedrow) {
        exit("Error !");
    } else {
        $userID = $fetchedrow['id'];
        $userName = $fetchedrow['username'];
        $tempPassword = $fetchedrow['temporarypass'];
        $useremail = $fetchedrow['emailaddress'];

        $query1 = $mysqli->query("UPDATE app_users SET registered = '1', token = '', temporarypass = '' WHERE id = '$userID'");
        
        header("Location: new-email-message.php");

        // Send the new email

        $domaininit = explode(".", $_SERVER['HTTP_HOST']);
        array_shift($domaininit);
        $domain = implode(".", $domaininit);
        $reqHost = $_SERVER['HTTP_HOST'];

        // Mention the content-type, since 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 account access";

        $message = "Hello, <br><br>
                    You can log in to your Roundpin account using the following credentials:<br><br>
                    username:  <b>".$userName."</b><br>
                    password:  <b>".$tempPassword."</b><br><br>
                    We highly recommend to change the password provided in this email with a new strong password. After you log in to Roundpin, click on the 'Account Settings'
                    wheel, click on 'Configure Account', then click on the 'Change Password' tab; enter your current password and a new password of at least 10 characters,
                    containing at least one letter, one digit and one special character.<br><br>
                    Thank you,<br>
                    Roundpin<br>
                    Host: '" . $reqHost . "'";

        mail($useremail, $subject, $message, $headers);
    }
}

?>