<?php include '../header.php'; ?>    
<?php include '../sidemenu.php'; ?>    
<style>
	.img-profile {
		width: 100%;              /* Make sure the image takes full width of the container */
		height: 239px;            /* Set a fixed height for the image */
		object-fit: cover;        /* This will ensure the image covers the container without distortion */
		border-radius: 10px;      /* Optional: to give the image rounded corners */
	}
</style>
<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">
                    User Account
                </h2>
                <button class="btn btn-outline-success" id="btnCreateNew">Create User Account</button>
            </div>
        </div>
    </div>
</div>

<div class="container" id="alertContainer1"></div>

<div class="page-body">
    <div class="container-xl">

        <div class="col-12">
            <div class="card">
                <!-- <div class="card-header d-flex justify-content-between">
                    <h3 class="card-title">Account List</h3>
                    
                </div> -->
                <div class="card-body">
					<div class="table-responsive">
						<table class="table table-vcenter card-table" id="myTable">
							<thead>
							<tr>
                                <th class="w-1">Photo</th>
                                <th>Name</th>
								<th>User Name</th>
								<th>Role Name</th>
								<th>Password</th>
								<th class="w-1"></th>
							</tr>
							</thead>
							<tbody>
							</tbody>
						</table>
						</div>
					</div>
				</div>
            </div>
        </div>
    </div>
</div>



<div class="modal fade" id="createAccountModel" tabindex="-1" aria-labelledby="reservationModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg " >
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create User Account</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="createAccountForm" method="POST" enctype="multipart/form-data">
                    <input type="hidden" class="form-control" id="txtAccountId" name="txtAccountId">
                    <input type="hidden" id="txtFormState" name="formState">
					
					<div class="row">
                        <div class="container" id="alertContainer2"></div>
						<div class="col-lg-5">
							<img class="img-profile img-thumbnail" id="output" src="<?=$app_url;?>img/dummy_user.png" alt="Selected image">
							<input type="file" name="image" id="imageInput" class="mt-3 form-control" onchange="loadFile(event)">
						</div>
						<div class="col-lg-6 offset-1">
                            <div class="mb-2">
								<label class="form-label">Name</label>
								<select class="form-select" id="cboStaff" name="cboStaff"></select>
							</div>
							<div class="mb-2">
								<label class="form-label">User Name</label>
								<input type="text" class="form-control" name="txtUserName" id="txtUserName" placeholder="Your name" autocomplete="off">
							</div>
							<div class="mb-2">
								<label class="form-label">Role Name</label>
								<select class="form-select" name="cboUserRole" id="cboUserRole"></select>
							</div>
							<div class="mb-2">
								<label class="form-label">Password</label>
								<input type="password" class="form-control" name="txtPassword" id="txtPassword" placeholder="Your password" autocomplete="off">
							</div>
							<div class="mb-2">
								<label class="form-label">Confirm Password</label>
								<input type="password" class="form-control" name="txtConfirmPassword" id="txtConfirmPassword" placeholder="Confirm your password" autocomplete="off">
							</div>
						</div>
					</div>
                    
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-outline-success" id="btnSave">Create</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" tabindex="-1" role="dialog" id="myModal">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" style="font-size: 20px;">Image Preview</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <center><img id="sf_img_large"/></center>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<?php include '../footer.php'; ?>

<script>    
$(function() {
    fillRole();
    getAll();
    getAllStaff();
});

function getAllStaff(){
    $("#cboStaff").find("option").remove();
    $("#cboStaff").append("<option value = ''></option>");
    $.ajax({
        url: APP_URL + "api/staff/get_all_rows.php"
    }).done(function(data) {
        $.each(data.records, function(i, v) {
            $("#cboStaff").append("<option value = '" + v.id + "'>" + v.name + "</option>");
        });
    });
}

$("#btnCreateNew").click(function(){
    $("#output").attr("src", "<?=$app_url;?>img/dummy_user.png");
    $("#btnSave").text("Create");
	$("#btnSave").removeClass("btn-outline-primary").addClass("btn-outline-success");

	$('#createAccountModel').modal('show');
	$("#txtAccountId").val("");
    $("#txtFormState").val("Create");

	// $("#txtRoleName").prop("disabled", false);
	// $("#btnSave").text("Create");
	// $("#btnSave").removeClass("btn-outline-primary").addClass("btn-outline-success");
	// clear();
});

function fillRole(){
    $("#cboUserRole").find("option").remove();
    $.ajax({
        url: APP_URL + "api/createrole/get_all_rows.php"
    }).done(function(data) {	
        $("#cboUserRole").append("<option></option>");
        $.each(data.records, function(i, v) {
            console.log(v);
            $("#cboUserRole").append("<option value= '" + v.id + "' data-id = '"+ v.id +"' >" + v.rolename + "</option>");
        });
    });
}

function getAll() {
    $("#myTable").find("tbody").find("tr").remove();
    $.ajax({
        url: APP_URL + "api/userlist/get_all_rows.php"
    }).done(function(data) {
        console.log(data);
        $.each(data.records, function(i, v) {
            console.log(v);
            $("#myTable").find("tbody")
            .append($('<tr>')
                .append("<td><img src='<?=$app_url;?>api/createaccount/" + v.profile + "' style='width:30px;height:30px' onclick='showImage(this)'/></td>")    
                .append("<td>" + v.staff_name + "</td>")
                .append("<td>" + v.username + "</td>")
                .append("<td>" + v.userrole + "</td>")
                .append("<td>" +
                    "<span class='password-mask' style='cursor: pointer;'>&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;</span>" +
                    "<span class='password-text d-none' style='cursor: pointer;'>" + v.password + "</span>" +
                "</td>")
                .append("<td><div class='btn-list flex-nowrap'><button class='btn btn-outline-primary btn-sm' onclick='editAccount(\"" + v.id + "\")'>Edit</button><button class='btn btn-outline-danger btn-sm' onclick='del(\"" + v.id + "\",this)'>Delete</button></div></td>")
            );
        });

        // Toggle password visibility on click
        $(document).on('click', '.password-mask, .password-text', function() {
            var passwordMask = $(this).closest('td').find('.password-mask');
            var passwordText = $(this).closest('td').find('.password-text');
            
            if (passwordMask.hasClass('d-none')) {
                passwordMask.removeClass('d-none'); // Show ***
                passwordText.addClass('d-none');   // Hide actual password
            } else {
                passwordMask.addClass('d-none');   // Hide ***
                passwordText.removeClass('d-none'); // Show actual password
            }
        });
    });
}






	$("#btnSave").click(function(){
		$("#createAccountForm").submit();
	});

	$("#createAccountForm").on('submit',(function(e) {
		e.preventDefault();
		var formState = $("#txtFormState").val();
        var staff_id = $("#cboStaff").val();
		var username = $("#txtUserName").val();
		var userrole = $('#cboUserRole').val();
		var password = $("#txtPassword").val();
		var confirmpassword = $("#txtConfirmPassword").val();
		if((staff_id.trim()=="" || username.trim()=="" || password.trim()=="" || confirmpassword.trim()=="" || userrole.trim()=="") ){
            showAlert("Please fill the boxes.", "warning",2);
		}else if((password.trim() != confirmpassword.trim())){
            showAlert("Passwords are unmatch! Please enter again.", "warning",2);
		}else if(password.trim().length<5){
            showAlert("Passwords should be at least 5.", "warning",2);
		}else{

			if(formState=="Edit"){	
				$("#txtUserName").prop("disabled", false);
			}
			
			$.ajax({
				url: APP_URL + "api/createaccount/create_update.php",
				type: "POST",             
				data: new FormData(this),
				// data1: JSON.stringify({userrole: userrole}),
				contentType: false,       
				cache: false,             
				processData:false,        
				success: function(data)   
				{

					if(data.message=="created"){
						showAlert("Role Created Successfully!", "success",1);
						$("#createAccountForm")[0].reset();
						getAll();
					    $('#createAccountModel').modal('hide');
					}else if(data.message=="updated"){
						showAlert("Role Updated Successfully!", "success",1);
						$("#createAccountForm")[0].reset();
						getAll();
                        $('#createAccountModel').modal('hide');
					}else if(data.message=="duplicate"){
						showAlert("Duplicate Entry!", "warning",2);
					}else{
						showAlert("Error on server side!", "danger",2);
					}
				}
			});
		}
	}));

function editAccount(id){
	// clear();
	$("#btnSave").text("Update");
	$("#btnSave").removeClass("btn-outline-success").addClass("btn-outline-primary");

	$('#createAccountModel').modal('show');
	$("#txtAccountId").val(id);
    $("#txtFormState").val("Update");



	$.ajax({
		url: APP_URL + "api/createaccount/get_one_row.php",
		type: "POST",
		data: JSON.stringify({ id: id })
	}).done(function(data){	
        $("#txtUserName").val(data.username);
        $("#output").attr('src', "<?=$app_url;?>/api/createaccount/" + data.profilepicture);
        $("#cboStaff").val(data.staff_id);
        $("#cboUserRole").val(data.userrole_id);
        $("#txtPassword").val(data.password);
        $("#txtConfirmPassword").val(data.password);
	});
}

function del(id, obj) {

$('#modal-delete').modal('show');
	$('#confirm-delete').off('click').on('click', function () {
		$.ajax({
			type: "POST",
			url: APP_URL + "api/userlist/delete.php",
			data: JSON.stringify({ id: id }),
			success: function (data) {
				if (data === "deleted") {
					$(obj).closest('tr').remove();
					showAlert("Account Deleted Successfully!", "success",1);
				} else {
					showAlert("Error on server side!", "danger",1);
				}
				$('#modal-delete').modal('hide');
			}
		});
	});
}

function showImage(obj) {
    $("#sf_img_large").removeClass("rotate_90");
    var aspectRatio = $(obj).width() / $(obj).height();
    $("#sf_img_large").attr("src", $(obj).attr("src"));
    $(".modal-body img").each(function() { 
        if (aspectRatio > 1) {
            $(this).addClass("rotate_90");
            $(this).css("width", "50%");
            $(this).css("height", "auto");
        } else {
            $(this).css("width", "50%");
            $(this).css("height", "auto");
        }
    });
    $(".modal-title").text($(obj).closest("tr").find("td").eq(2).text());
    $("#myModal").modal('show');
}
</script>
