<?php
header("Content-Type: application/json");

include "./../lib/send_reply_json.php";
include "./../setup/connect_db.php";

$maestroID = $_POST["maestro_id"];
$registeredPW = $_POST["registered_pw"];
$newPW = $_POST["new_pw"];


$countResult = maestro_registered_password($maestroID, $registeredPW);
if($countResult === null || $countResult < 1) {
	set_error_message("입력하신 [현재 암호]가 맞지 않습니다.");
	send_result_fail();
	exit;
}

update_maestro_password($maestroID, $newPW);

send_result_success();
exit;


function maestro_registered_password($maestro_id, $registeredPW) {
	global $db_conn;

	$query = "
		SELECT COUNT(MaestroID)
		FROM maestro
		WHERE MaestroID = ? AND Password = PASSWORD(?)
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("is", $maestro_id, $registeredPW);
	$stmt->execute();
	$stmt->bind_result($countResult);
	// while($stmt->fetch())
	$stmt->fetch();
	$stmt->close();

	return $countResult;
}

function update_maestro_password($maestroID, $newPW) {
	global $db_conn;

	$query = "
		UPDATE maestro
		SET Password = PASSWORD(?)
		WHERE MaestroID = ?
	";
	$stmt = $db_conn->prepare($query);
	$stmt->bind_param("si", $newPW, $maestroID);
	$stmt->execute();
}

?>