<?php
/**
 *  Copyright (C) 2022, 2024  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();

$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'];

        $reg = 1;
        $crtoken = '';
        $temppass = '';
        $query1 = $mysqli->prepare("UPDATE app_users SET registered = ?, token = ?, temporarypass = ? WHERE id = ?");
        $query1->bind_param("issi", $reg, $crtoken, $temppass, $userID);
        $query1->execute();
        
        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);
    }
}

?>
