<?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();

 // header('Set-Cookie: PHPSESSID= ' . session_id() . '; SameSite=strict; Secure=true; HttpOnly=true;');

$retrievedToken = $_GET['token'];
$retrievedEmail = $_GET['newemail'];

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

  define('ACCESSCONST', TRUE);

  require('db-connect.php');

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

    if (!$fetcheddbdata) {

        exit("Error !");

    } else {

        $userName = $fetcheddbdata['username'];

        $crtoken = '';
        $queryupemailandtoken = $mysqli->prepare("UPDATE app_users SET emailaddress = ?, token = ? WHERE username = ?");
        $queryupemailandtoken->bind_param("sss", $retrievedEmail, $crtoken, $userName);
        $queryupemailandtoken->execute();

        header("Location: email-address-changed.php");
    }
}

?>
