<?php
include '../db/db.php';
session_start();
$log = htmlspecialchars(trim($_SESSION['user']), ENT_QUOTES, 'UTF-8');
$log_lang = htmlspecialchars(trim($_SESSION['lang']), ENT_QUOTES, 'UTF-8');

$menu = htmlspecialchars(trim($_SESSION['menu']), ENT_QUOTES, 'UTF-8');
$emp_id = htmlspecialchars(trim($_SESSION['emp_id']), ENT_QUOTES, 'UTF-8');

if (empty($log)) {
	$redirectUrl = "index.php";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";

} else {

	$sqlu = "SELECT * FROM user_priv_q WHERE emp_id='$emp_id' AND user='$log' AND menu_id='$menu'";
	$resultu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($resultu);

	if($countu == 1){
		$rowc = mysqli_fetch_assoc($resultu);
		$user_id = $rowc['user_id'];

		/****************************** Update *************************************/
		
		if(isset($_POST['new_pw'])) {
			$new_pw = htmlspecialchars(strip_tags(trim($_POST['new_pw'])), ENT_QUOTES, 'UTF-8');
			$old_pw = htmlspecialchars(strip_tags(trim($_POST['old_pw'])), ENT_QUOTES, 'UTF-8');
			
			$sqlpw = mysqli_fetch_assoc(mysqli_query($conn, "SELECT pass FROM user_acc_tbl WHERE id='$user_id' AND user='$log'"));
			$upw = $sqlpw['pass'];
			
			if(empty($new_pw) || empty($old_pw)) {
				echo 'empty';
			
			} else {
				$old_upw = hash('sha256', $old_pw);
				
				if($old_upw == $upw) {
					$password = hash('sha256', $new_pw);
					
					$sql = "UPDATE user_acc_tbl SET pass='$password' WHERE id='$user_id' AND user='$log'";
					$stmt_log = mysqli_query($conn, $sql);
					
					if($stmt_log === false) {
						echo 'error';
					
					} else {
						echo 'success';
					}
		
				} else {
					echo 'incorrect';
				}
			}
		}
		
		/******************************************************************/		

	} else{
		$redirectUrl = "index.php";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";	
	}
}
?>