<?php
require_once(__DIR__.'/../inc/role_guard.php');

/*
 ROLES PERMITIDOS:
 - ADMIN
 - GESTOR
 - PO
 - SUPERVISOR
*/
require_role(['ADMIN','GESTOR','PO','SUPERVISOR']);

/* =========================
   DATOS DEL USUARIO LOGUEADO
========================= */
$user = $conn->query(
    "SELECT * FROM employee_list 
     WHERE id = '".$_settings->userdata('id')."'"
);

if($user && $user->num_rows > 0){
    foreach($user->fetch_array() as $k => $v){
        if(!is_numeric($k))
            $$k = $v;
    }
}
?>

<?php if($_settings->chk_flashdata('success')): ?>
<script>
	alert_toast("<?php echo $_settings->flashdata('success') ?>",'success')
</script>
<?php endif; ?>

<div class="card card-outline card-primary">
	<div class="card-body">
		<div class="container-fluid">
			<div id="msg"></div>

			<form action="" id="manage-user">
				
				<!-- SIEMPRE EL ID DE SESIÓN -->
				<input type="hidden" name="id" 
                       value="<?php echo $_settings->userdata('id') ?>">

				<input type="hidden" name="code" 
                       value="<?php echo $_settings->userdata('code') ?>">

				<input type="hidden" name="generated_password" value="">

				<div class="row">
					<div class="form-group col-md-4">
						<input type="text" name="firstname" required
							   class="form-control form-control-sm form-control-border"
							   value="<?= $firstname ?? '' ?>">
						<small class="mx-2">Nombre</small>
					</div>

					<div class="form-group col-md-4">
						<input type="text" name="middlename"
							   class="form-control form-control-sm form-control-border"
							   value="<?= $middlename ?? '' ?>">
						<small class="mx-2">Segundo Nombre</small>
					</div>

					<div class="form-group col-md-4">
						<input type="text" name="lastname" required
							   class="form-control form-control-sm form-control-border"
							   value="<?= $lastname ?? '' ?>">
						<small class="mx-2">Apellido</small>
					</div>
				</div>

				<div class="row">
					<div class="form-group col-md-4">
						<select name="gender"
								class="form-control form-control-sm form-control-border"
								required>
							<option value="Male" <?= ($gender ?? '')=='Male'?'selected':'' ?>>Masculino</option>
							<option value="Female" <?= ($gender ?? '')=='Female'?'selected':'' ?>>Femenino</option>
						</select>
						<small class="mx-2">Género</small>
					</div>

					<div class="form-group col-md-4">
						<input type="text" name="department" required
							   class="form-control form-control-sm form-control-border"
							   value="<?= $department ?? '' ?>">
						<small class="mx-2">Departamento</small>
					</div>

					<div class="form-group col-md-4">
						<input type="text" name="position" required
							   class="form-control form-control-sm form-control-border"
							   value="<?= $position ?? '' ?>">
						<small class="mx-2">Cargo</small>
					</div>
				</div>

				<div class="row">
					<div class="form-group col-md-10">
						<input type="email" name="email" required
							   class="form-control form-control-sm form-control-border"
							   value="<?= $email ?? '' ?>">
						<small class="mx-2">Correo institucional</small>
					</div>
				</div>

				<!-- PASSWORD -->
				<div class="row">
					<div class="form-group col-md-10">
						<div class="input-group input-group-sm">
							<input type="password" name="password" id="password"
								   class="form-control form-control-sm form-control-border">
							<div class="input-group-append">
								<span class="input-group-text bg-transparent border-0">
									<a href="javascript:void(0)" class="pass_view text-muted">
										<i class="fas fa-eye-slash"></i>
									</a>
								</span>
							</div>
						</div>
						<small class="mx-2">Nueva Contraseña</small>
					</div>
				</div>

				<div class="row">
					<div class="form-group col-md-10">
						<div class="input-group input-group-sm">
							<input type="password" id="cpass"
								   class="form-control form-control-sm form-control-border">
							<div class="input-group-append">
								<span class="input-group-text bg-transparent border-0">
									<a href="javascript:void(0)" class="pass_view text-muted">
										<i class="fas fa-eye-slash"></i>
									</a>
								</span>
							</div>
						</div>
						<small class="mx-2">Confirmar Contraseña</small>
					</div>
				</div>

				<small class="text-muted">
					Deja las contraseñas en blanco si no deseas cambiarlas
				</small>

				<div class="form-group mt-3">
					<label>Avatar</label>
					<div class="custom-file">
						<input type="file" class="custom-file-input"
							   name="img"
							   onchange="displayImg(this)">
						<label class="custom-file-label">Seleccionar imagen</label>
					</div>
				</div>

				<div class="form-group d-flex justify-content-center">
					<img src="<?= validate_image($avatar ?? '') ?>"
						 id="cimg"
						 class="img-thumbnail">
				</div>

			</form>
		</div>
	</div>

	<div class="card-footer">
		<button class="btn btn-primary btn-sm" form="manage-user">
			Actualizar Perfil
		</button>
	</div>
</div>

<style>
#cimg{
	height:15vh;
	width:15vh;
	object-fit:cover;
	border-radius:50%;
}
</style>

<script>
function displayImg(input){
	if(input.files && input.files[0]){
		var reader = new FileReader();
		reader.onload = e => $('#cimg').attr('src',e.target.result);
		reader.readAsDataURL(input.files[0]);
	}
}

$('.pass_view').click(function(){
	let i = $('#password,#cpass');
	let t = i.attr('type');
	i.attr('type',t=='password'?'text':'password');
	$(this).html(t=='password' ? '<i class="fas fa-eye"></i>' : '<i class="fas fa-eye-slash"></i>');
});

$('#manage-user').submit(function(e){
	e.preventDefault();

	if($('#password').val() !== $('#cpass').val()){
		alert_toast('Las contraseñas no coinciden','error');
		return;
	}

	start_loader();

	$.ajax({
		url:_base_url_+'classes/Users.php?f=save_employee',
		data:new FormData(this),
		contentType:false,
		processData:false,
		method:'POST',
		dataType:'json',
		success:function(resp){
			if(resp.status==='success'){
				location.reload();
			}else{
				alert_toast(resp.msg || 'Error','error');
			}
			end_loader();
		}
	});
});
</script>
