<?php
include "../../../backend/db/db.php";
session_start();
if(isset($_SESSION['user'])) {
	$log = htmlspecialchars(trim($_SESSION['user']), ENT_QUOTES, 'UTF-8');
}
if (empty($log)) {
	$redirectUrl = "../../../home";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";

} else {

	$sqlu = "SELECT id, pwd FROM contractor_reg WHERE SIDA_no='$log' and del='0'";
	$resultu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($resultu);

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

		/****************************** 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');

			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 contractor_reg SET pwd='$password' WHERE id='$user_id' AND SIDA_no='$log'";
					$stmt_log = mysqli_query($conn, $sql);
					
					if($stmt_log === false) {
						echo 'error';
					
					} else {
						echo 'success';
					}
		
				} else {
					echo 'incorrect';
				}
			}
		}

		/******************************************************************/		

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