<?= $this->extend('layouts/main.php') ?>

<?= $this->section('content') ?>
<div class="row">
	<div class="col-6">
		<div class="card">
			<div class="card-body">
				<div class='card-title'> Password Editor </div>		
				<div id='alertPass'></div>
				<table class="table table-sm table-borderless">
					<tr class="align-middle"> <th>Password</th> <th>:</th> <td><input class='form-control' type='password' id='pass1'/></td> </tr>
					<tr class="align-middle"> <th>Conf. Password</th> <th>:</th> <td><input class='form-control' type='password' id='pass2'/></td> </tr>
				</table>
				<button class='btn btn-sm btn-primary' onclick='savePass()'>Save</button>
				<button class='btn btn-sm btn-secondary' data-bs-dismiss="modal">Cancel</button>
			</div>
		</div>
	</div>
</div>
<?= $this->endSection() ?>

<?= $this->section('script') ?>
<script>
window.onload = function() {
	document.getElementById("pass1").focus();
}

function savePass() {
	var userid = '<?=$_SESSION['userid'];?>';
	var pass1 = $("#pass1").val();
	var pass2 = $("#pass2").val();
	if(pass1 == pass2) {
		let url = '<?=base_url('');?>api/users/savePass/'+userid ;
		let data = { userid: userid, pass : pass1 };
		$.ajax({
			url: url,
			method: "POST",
			data: data,
			success: function(response) {
				$("#pass1").val('');
				$("#pass2").val('');
				$('#alertPass').html( 
					"<div class='alert alert-success alert-dismissible fade show' role='alert'> "+
						"Password updated!" +
						"<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>"+
					"</div>"
				);
			},
			error: function(response) {
				console.log(response.responseJSON)
			}
		});
	} else {
		$('#alertPass').html( 
			"<div class='alert alert-danger alert-dismissible fade show' role='alert'> "+
				"Password is not the same!" +
				"<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>"+
			"</div>"
		);
	}
}
</script>
<?= $this->endSection() ?>