<?php
require 'acdet.php';

$userName = $_POST['userName'];
$response = "";

$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

$userName = $mysqli->real_escape_string($userName);

$sqlName = "SELECT * FROM accounts WHERE username = '$userName'";
$resultName = $mysqli->query($sqlName);

if($resultName -> num_rows < 1){
    $response = "noUser";
} else {
    //get email using username
    /*
    $sqlMail = "SELECT username = '$userName', email FROM accounts";
    $resultMail = $mysqli->query($sqlMail);
    $row = $resultMail->fetch_assoc();
    */
    
    $row = $resultName->fetch_assoc();
    $userEmail = $row["email"];

    
    //generate new email
    function generateRandomString() {
        $passLength = 8;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $passLength; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
    $newPass = generateRandomString();
    
    //$newPass = "parola12";
    //pass crypt algo
    $iterations = 1000;
    $salt = count($userName) * 23;
    $hashPass = hash_pbkdf2("sha256", $newPass, $salt, $iterations, 25);

    //update with new generated password
    $sqlMailUpdate = "UPDATE accounts SET userpass = '$hashPass' WHERE username = '$userName'";

    if($mysqli->query($sqlMailUpdate) === true){

        //send email
        $subject = "GuardCam Password Reset";
        $message = "This is your new auto generated password for myguardcam.com: ".$newPass
        ."\r\n"
        ."\r\n"."Do not replay to this email !";
        $headers = "From: " . "register@myguardcam.com";
        mail($userEmail, $subject, $message, $headers);

        $response = "An email with an auto-generated password was sent to: " .$userEmail. ". Please check your inbox and spam folder. 
        If you don't get any email after one hour, try again.";
    }
}

echo $response;

$mysqli->close();


?>