<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" session="false"%>
<%@ include file="/WEB-INF/jsp/include/taglib.jsp"%>

<form id="password-form">
	<div class="row g-3">
		<div class="col-md-12">
			<div class="row">
				<label class="col-sm-4 col-form-label text-sm-end required" for="currentPassword">
				현재 비밀번호
				</label>
				<div class="col-sm-8">
					<input name="currentPassword" type="password" required class="form-control" />
				</div>
			</div>
		</div>
		<div class="col-md-12">
			<div class="row">
				<label class="col-sm-4 col-form-label text-sm-end required" for="password">
				새 비밀번호
				</label>
				<div class="col-sm-8">
					<input name="password" type="password" required class="form-control" />
				</div>
			</div>
		</div>
		<div class="col-md-12">
			<div class="row">
				<label class="col-sm-4 col-form-label text-sm-end required" for="confirmPassword">
				새 비밀번호 확인
				</label>
				<div class="col-sm-8">
					<input name="confirmPassword" type="password" required class="form-control" />
				</div>
			</div>
		</div>
	</div>
	<div class="row mt-4 justify-content-end">
		<div class="col-md-6">
			<div class="row justify-content-end">
				<div class="col-sm-3">
					<button type="button" onclick="validPassword();" class="btn btn-primary">저장</button>
				</div>
			</div>
		</div>
	</div>
</form>
<script>
	function validPassword(){
		if($("#password-form input[name='currentPassword']").val() == ""){
			dialog.alert("현재 비밀번호를 입력하세요.");
			return;
		}
		if($("#password-form input[name='password']").val() == ""){
			dialog.alert("새 비밀번호를 입력하세요.");
			return;
		}
		if($("#password-form input[name='confirmPassword']").val() == ""){
			dialog.alert("새 비밀번호 확인을 입력하세요.");
			return;
		}
		
		let match = Array.from(document.querySelectorAll("input[name='password'],input[name='confirmPassword']"))
			.map(input => input.value)
			.reduce((total, current) => total == current);
		if (!match) {
			dialog.alert({
				content:"새 비밀번호와 새 비밀번호 확인이 다릅니다.",
				onClose:function(){
					document.querySelector("input[name='confirmPassword']").focus();
				}
			});
			return;
		}
		
		savePassword();
	}
	
	function savePassword(){
		
		ajax.post({
			url : wctx.url("/user/changePassword.do"),
			data : { 
				userIDs : MY_INFO.id,
				password : $("#password-form input[name='password']").val(),
				currentPassword : $("#password-form input[name='currentPassword']").val(),
				init : false
			},
			success : (resp) => {
				if(resp.saved){
					dialog.alert("비밀번호 변경에 성공하였습니다.");
					dialog.close("changePasswordDialog");
				} else {
					dialog.alert("비밀번호 변경에 실패하였습니다.");
				}
			}
		});
	}
</script>