<?php

session_start();



$userid=$_POST['user_id'];

$old_password=$_POST['old_password'];

$new_password=$_POST['new_password'];

$new_password1=$_POST['new_password1'];

$_GET['showq']=$_POST['showq'];



if ($new_password!=$new_password1)
{
	$_SESSION['loginerror']="New passwords do not match";
	header("Location: ./login.php");
	exit;
}
elseif ($new_password==$old_password)
{
    $_SESSION['loginerror']="New password is same as old password";
    header("Location: ./login.php");
    exit;
}



include($_SESSION['adminpath']."/dbopen.php");



$query = "SELECT value as salt FROM  ootp_sql_admin WHERE setting='salt' AND identifier = $userid;";

if ($_GET['showq']==1) {echo "$query<br/>\n";}

$result=mysqli_query($db,$query);

$row=mysqli_fetch_array($result);

$escapedPW=addslashes($old_password);

$saltedPW =  $escapedPW . $row['salt'];

$hashedPW = hash('sha256', $saltedPW);



$query = "SELECT identifier as human_manager_id FROM ootp_sql_admin WHERE identifier='$userid' AND setting='password' AND value='$hashedPW'; ";

if ($_GET['showq']==1) {echo "$query<br/>\n";}

$result=mysqli_query($db,$query);

if (mysqli_num_rows($result))     ## Successful login

{

	$escapedPW=addslashes($new_password);

	$salt=bin2hex(random_bytes(32));

	$saltedPW=$escapedPW . $salt;



	$hashedPW = hash('sha256', $saltedPW);

	

	$query="UPDATE ootp_sql_admin SET value='$salt' WHERE identifier='$userid' AND setting='salt';\n";

	if ($_GET['showq']==1) {echo "$query<br/>\n";}

	mysqli_query($db,$query);

	$query="UPDATE ootp_sql_admin SET value='$hashedPW' WHERE identifier='$userid' AND setting='password';\n";

	if ($_GET['showq']==1) {echo "$query<br/>\n";}

	mysqli_query($db,$query);



	$_SESSION['loginerror']="Password changed successfully!";

}

else    ## Incorrect old password

{

	$_SESSION['loginerror']="Incorrect old password entered";

}



mysqli_close($db);



if ($_GET['showq']!=1) {header("Location: ./login.php");}



?>

