@extends('theme::user.layouts.app')


@section('content')

<div class="user-management-page">
	<div class="title-wrapper">
		<h2 class="page-title">{{ __("User") }}</h2>
		<button type="button" class="btn blue-btn" data-bs-toggle="modal" data-bs-target="#newUserModal">{{ __("New user") }}</button>
	</div>
	<div class="custom-nav-tabs">
		<ul class="nav nav-tabs nav-justified">
			<li class="nav-item">
				<a class="nav-link active" data-bs-toggle="tab" href="#userList">
					<img src="{{ asset('themes/tailwind/images/user-icon.png') }}">
					{{ __("User List") }}
				</a>
			</li>
			<li class="nav-item">
				<a class="nav-link" data-bs-toggle="tab" href="#userAccessRight">
					<img src="{{ asset('themes/tailwind/images/security-safe.png') }}">
					{{ __("User Access Right") }}
				</a>
			</li>
			<li class="nav-item">
				<a class="nav-link" data-bs-toggle="tab" href="#accessLog">
					<img src="{{ asset('themes/tailwind/images/access-log-icon.png') }}">
					{{ __("Access Log") }}
				</a>
			</li>
		</ul>
		
		<!-- Tab panes -->
		<div class="tab-content">
			<div class="tab-pane active" id="userList">
				<div class="table-responsive">
					<table class="table custom-table">
						<thead>
							<tr>
								<th scope="col">{{ __("First name") }}</th>
								<th scope="col">{{ __("Last name") }}</th>
								<th scope="col">{{ __("User email") }}</th>
								<th scope="col">{{ __("User role") }}</th>
								<th scope="col">{{ __("Status") }}</th>
								<th scope="col">{{ __("Action") }}</th>
							</tr>
						</thead>
						<tbody>
							@foreach($company_users as $user)
								<tr>
									<td>{{ $user->first_name }}</td>
									<td>{{ $user->last_name }}</td>
									<td>{{ $user->email }}</td>
									<td>{{ $user->userRole->display_name }}</td>
									<td><span class="green-text">{{ $user->status }}</span></td>
									<td>
										<input type="hidden" id="user-{{ $user->id }}-details" value="{{ json_encode($user) }}" >
										<div class="table-actions">
											<!-- <a href="#" class="action-btn text-underline sky-blue-text" data-bs-toggle="modal" data-bs-target="#userDetailsModal">View</a>
											<span class="action-separator">|</span> -->
											<a href="#" class="action-btn text-underline sky-blue-text btn-edit-user" data-user-id="{{ $user->id }}" data-bs-toggle="modal" data-bs-target="#userDetailsModal" >{{ __("Edit") }}</a>
											<span class="action-separator">|</span>
											<a href="#" class="action-btn text-underline red-text btn-delete-user" data-user-id="{{ $user->id }}" >{{ __("Archive") }}</a>
										</div>
									</td>
								</tr>
							@endforeach
						</tbody>
					</table>
				</div>
			</div>
			<div class="tab-pane fade" id="userAccessRight">
				<div class="table-responsive">
					<table class="table custom-table">
						<thead>
							<tr>
								<th scope="col">{{ __("Access right") }}</th>
								@foreach($roles as $role)
									<th scope="col">{{ $role->display_name }}</th>
								@endforeach
							</tr>
						</thead>
						<tbody>
							@foreach($permission_group as $group)
							<tr style="background: #F4F7FA;">
								<td colspan="5" class="fw-600">{{ $group->name }}</td>
							</tr>
								@foreach($group->permissions as $permission)
									<tr>
										<td>{{ $permission->display_name }}</td>
										@foreach($roles as $role)
											<td>
												<div class="custom-radio-checkbox">
													<input type="checkbox" id="checkbox-{{ $permission->id }}-{{ $role->id }}" class="update_permission" value="" data-permission-id="{{ $permission->id }}" data-role-id="{{ $role->id }}" {{ checkRoleHasPermission($permission->id, $role->id) ? 'checked' : '' }} >
													<label for="checkbox-{{ $permission->id }}-{{ $role->id }}">
													</label>
												</div>
											</td>
										@endforeach
									</tr>
								@endforeach
							@endforeach
						</tbody>
					</table>
				</div>
			</div>
			<div class="tab-pane fade" id="accessLog">
				<div class="table-responsive">
					<table class="table custom-table">
						<thead>
							<tr>
								<th scope="col">{{ __("User email") }}</th>
								<th scope="col">{{ __("Date") }}</th>
								<th scope="col">{{ __("Time") }}</th>
							</tr>
						</thead>
						<tbody>
							@foreach($user_logs as $log)
								<tr>
									<td>{{ $log->description }}</td>
									<td>{{ explode(' ', $log->created_at)[0] }}</td>
									<td>{{ explode(' ', $log->created_at)[1] }}</td>
								</tr>
							@endforeach
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</div>

{{-- Add User Modal --}}
<div class="modal fade custom-modal style2" id="newUserModal" tabindex="-1" aria-labelledby="newUserModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-xl modal-dialog-centered">
		<div class="modal-content mx-auto">
			<div class="modal-body p-0">
				<p class="modal-title">{{ __("New User") }}</p>
				<div id="create_user_error" ></div>
				<form id="form_create_user" action="{{ route('wave.management.create.user') }}" method="POST" class="theme-form" >
					<div class="row">
						<div class="col-md-6">
							<div class="row mb-4 align-items-center">
								<div class="col-auto">
									<label class="col-form-label">{{ __("First name") }}</label>
								</div>
								<div class="col">
									<input type="text" class="form-control" name="first_name" id="create_first_name" value="" required>
								</div>
							</div>
						</div>
						<div class="col-md-6">
							<div class="row mb-4 align-items-center">
								<div class="col-auto">
									<label class="col-form-label">{{ __("New Password") }}</label>
								</div>
								<div class="col">
									<div class="password-wrapper">
										<input type="password" class="form-control" name="password" id="create_password" value="" autocomplete="off" required>
										<img class="mx-auto password-hide-show" src="{{ asset('themes/tailwind/images/password-hide-show.png') }}">
									</div>
								</div>
							</div>
						</div>
						<!-- <div class="col-md-6">
							<div class="row mb-4 align-items-center">
								<div class="col-auto">
									<label class="col-form-label">Current Password</label>
								</div>
								<div class="col">
									<input type="password" class="form-control" name="create_password" id="create_password" value="">
								</div>
							</div>
						</div> -->
					</div>
					<div class="row">
						<div class="col-md-6">
							<div class="row mb-4 align-items-center">
								<div class="col-auto">
									<label class="col-form-label">{{ __("Last name") }}</label>
								</div>
								<div class="col">
									<input type="text" class="form-control" name="last_name" id="create_last_name" value="" required>
								</div>
							</div>
						</div>
						<div class="col-md-6">
							<div class="row mb-4 align-items-center">
								<div class="col-auto">
									<label class="col-form-label">{{ __("Confirm Password") }}</label>
								</div>
								<div class="col">
									<div class="password-wrapper">
										<input type="password" class="form-control" name="confirm_password" id="create_confirm_password" value="" required>
										<img class="mx-auto password-hide-show" src="{{ asset('themes/tailwind/images/password-hide-show.png') }}">
									</div>
								</div>
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-md-6">
							<div class="row mb-4 align-items-center">
								<div class="col-auto">
									<label class="col-form-label">{{ __("Phone") }}</label>
								</div>
								<div class="col">
									<input type="text" class="form-control" name="phone" id="create_phone" value="" required>
								</div>
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-md-6">
							<div class="row mb-4 align-items-center">
								<div class="col-auto">
									<label class="col-form-label">{{ __("Email") }}</label>
								</div>
								<div class="col">
									<input type="email" class="form-control" name="email" id="create_email" value="" autocomplete="off" required>
								</div>
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-md-6">
							<div class="row mb-4 align-items-center">
								<div class="col-auto">
									<label class="col-form-label">{{ __("Role") }}</label>
								</div>
								<div class="col">
									<select class="w-100" name="role_id" id="create_role" required>
										<option value="" selected>-- {{ __("Select Role") }} --</option>
										@foreach($roles as $role)
											<option value="{{ $role->id }}" >{{ $role->display_name }}</option>
										@endforeach
									</select>
								</div>
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-md-6">
							<div class="row mb-4 align-items-center">
								<div class="col-auto">
									<label class="col-form-label">{{ __("Status") }}</label>
								</div>
								<div class="col">
									<select class="w-100" name="status" id="create_status" required>
										<option value="active" selected>{{ __("Active") }}</option>
										<option value="inactive">{{ __("Inactive") }}</option>
									</select>
								</div>
							</div>
						</div>
					</div>

					<div class="d-flex align-items-center justify-content-center">
						<button type="submit" class="btn blue-btn mx-3">{{ __("Save") }}</button>
						<button type="button" class="btn red-btn mx-3" data-bs-dismiss="modal">{{ __("Cancel") }}</button>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>

<form action="{{ route('wave.management.delete.user') }}" id="user_delete_form" >
	<input type="hidden" name="user_id" id="delete_user_id" value="" >
</form>

{{-- User Detail Modal --}}
<div class="modal fade custom-modal style2" id="userDetailsModal" tabindex="-1" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-lg modal-dialog-centered">
		<div class="modal-content mx-auto">
			<div class="modal-body p-0">
				<p class="modal-title">{{ __("User Detail") }}</p>
				<div id="update_user_error" ></div>
				<form action="{{ route('wave.management.update.user') }}" id="update_user_form" class="theme-form">
					<input type="hidden" name="user_id" id="update_user_id" value="" >
					<div class="row mb-4 align-items-center">
						<div class="col-auto">
							<label class="col-form-label">{{ __("First name") }}</label>
						</div>
						<div class="col">
							<input type="text" class="form-control" value="" name="first_name" id="update_first_name" required>
						</div>
					</div>
					<div class="row mb-4 align-items-center">
						<div class="col-auto">
							<label class="col-form-label">{{ __("Last name") }}</label>
						</div>
						<div class="col">
							<input type="text" class="form-control" value="" name="last_name" id="update_last_name" required>
						</div>
					</div>
					<div class="row mb-4 align-items-center">
						<div class="col-auto">
							<label class="col-form-label">{{ __("Phone") }}</label>
						</div>
						<div class="col">
							<input type="number" class="form-control" value="" name="phone" id="update_phone" required>
						</div>
					</div>
					<div class="row mb-4 align-items-center">
						<div class="col-auto">
							<label class="col-form-label">{{ __("Email") }}</label>
						</div>
						<div class="col">
							<input type="email" class="form-control" value="" name="email" id="update_email" required>
						</div>
					</div>
					<div class="row mb-4 align-items-center">
						<div class="col-auto">
							<label class="col-form-label">{{ __("Password") }}</label>
						</div>
						<div class="col">
							<input type="password" class="form-control" value="" name="password" id="update_password">
						</div>
					</div>
					<div class="row mb-4 align-items-center">
						<div class="col-auto">
							<label class="col-form-label">{{ __("Confirm Password") }}</label>
						</div>
						<div class="col">
							<input type="password" class="form-control" value="" name="confirm_password" id="update_confirm_password">
						</div>
					</div>
					<div class="row mb-4 align-items-center">
						<div class="col-auto">
							<label class="col-form-label">{{ __("Role") }}</label>
						</div>
						<div class="col">
							<select class="w-100" name="role_id" id="update_role_id" required>
								<option value="" selected>-- {{ __("Select Role") }} --</option>
								@foreach($roles as $role)
									<option value="{{ $role->id }}" >{{ $role->display_name }}</option>
								@endforeach
							</select>
						</div>
					</div>
					<div class="row mb-4 align-items-center">
						<div class="col-auto">
							<label class="col-form-label">{{ __("Status") }}</label>
						</div>
						<div class="col">
							<select class="w-100" name="status" id="update_status" required>
								<option value="active" selected>{{ __("Active") }}</option>
								<option value="inactive">{{ __("Inactive") }}</option>
							</select>
						</div>
					</div>

					<div class="d-flex align-items-center justify-content-center">
					<button type="submit" class="btn blue-btn mx-3">{{ __("Update") }}</button>
						<button type="button" class="btn red-btn" data-bs-dismiss="modal">{{ __("Back") }}</button>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>
<input type="hidden" id="add_permission_role_url" value="{{ route('user.role.add-permission') }}" >
<input type="hidden" id="remove_permission_role_url" value="{{ route('user.role.remove-permission') }}" >
@endsection

@section('script')
	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        $(function() {
			$.ajaxSetup({
				headers: {
					'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
				}
			});
			var add_permission_role_url = $('#add_permission_role_url').val();
			var remove_permission_role_url = $('#remove_permission_role_url').val();
            $('.password-hide-show').click(function() {
                var type = $(this).parent().find('input').attr('type');

                if (type == 'password') {
                    $(this).parent().find('input').attr('type', 'text');
                }
                else {
                    $(this).parent().find('input').attr('type', 'password');
                }
            });

			$(document).on('submit', '#form_create_user', function(e){
				e.preventDefault();
				$('#create_user_error').html('');
				if ($('#create_password').val() != $('#create_confirm_password').val()) {
					$('#create_user_error').html('<div class="alert alert-danger" role="alert">Password didint match!</div>');
					return;
				}

				$.ajax({
					url: $(this).attr('action'),
					type: 'post',
					data: $(this).serialize(),
					dataType:'json',
					success:function(response) {
						console.log('response', response);
						if (response.success) {
							$('#create_user_error').html(`<div class="alert alert-success" role="alert">${response.message}</div>`);
							setTimeout(() => {
								location.reload();
							}, 2000);
						}
					},
					error:function(err) {
						var error = err.responseJSON;
						$('#create_user_error').html(`<div class="alert alert-danger" role="alert">${error.message}</div>`);
					}
				});
			});

			$(document).on('click', '.btn-edit-user', function(e){
				e.preventDefault();
				let user_id = $(this).attr('data-user-id');
				let user_data = $('#user-' + user_id + '-details').val();
				user_data = JSON.parse(user_data);
				
				$('#update_user_error').html('');
				$('#update_first_name').val(user_data.first_name);
				$('#update_last_name').val(user_data.last_name);
				$('#update_phone').val(user_data.phone);
				$('#update_email').val(user_data.email);
				$('#update_role_id').val(user_data.role_id);
				$('#update_status').val(user_data.status);
				$('#update_user_id').val(user_data.id);
			});

			$(document).on('submit', '#update_user_form', function(e){
				e.preventDefault();
				let password = $('#update_password').val();
				let confirm_password = $('#update_confirm_password').val();

				if (password != '' && confirm_password != '') {
					if (passowrd != confirm_passowrd) {
						$('#update_user_error').html(`<div class="alert alert-danger" role="alert">Password didint match!</div>`);
						return;
					}
				}

				$.ajax({
					url: $(this).attr('action'),
					type: 'post',
					data: $(this).serialize(),
					dataType:'json',
					success:function(response) {
						if (response.success) {
							$('#update_user_error').html(`<div class="alert alert-success" role="alert">${response.message}</div>`);
							setTimeout(() => {
								location.reload();
							}, 2000);
						} else {
							$('#update_user_error').html(`<div class="alert alert-danger" role="alert">${response.message}</div>`);
						}
					},
					error:function(err) {
						var error = err.responseJSON;
						$('#update_user_error').html(`<div class="alert alert-danger" role="alert">${error.message}</div>`);
					}
				});

			});

			$(document).on('click', '.btn-delete-user', function(e){
				e.preventDefault();
				let user_id = $(this).attr('data-user-id');

				$('#delete_user_id').val(user_id);

				Swal.fire({
				title: 'Are you sure?',
				text: "You won't be able to revert this!",
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: 'Yes, delete it!'
				}).then((result) => {
					if (result.isConfirmed) {
						$.ajax({
							url: $('#user_delete_form').attr('action'),
							type: 'post',
							data: $('#user_delete_form').serialize(),
							dataType:'json',
							success:function(response) {
								if (response.success) {
									Swal.fire(
										'Deleted!',
										response.message,
										'success'
									);
									setTimeout(() => {
										location.reload();
									}, 2000);
								}
							},
							error:function(err) {
								var error = err.responseJSON;
							}
						});
					}
				});
			});

			$(document).on('click', '.update_permission', function(){
				var permission_id = $(this).attr('data-permission-id');
				var role_id = $(this).attr('data-role-id');

				console.log('permission_id', permission_id);
				console.log('role_id', role_id);

				if ($(this).prop('checked')) {
					$.ajax({
						url: add_permission_role_url,
						type: 'post',
						data: {
							permission_id: permission_id,
							role_id: role_id,
						},
						dataType:'json',
						success:function(response) {
						}
					});
				} else {
					$.ajax({
						url: remove_permission_role_url,
						type: 'post',
						data: {
							permission_id: permission_id,
							role_id: role_id,
						},
						dataType:'json',
						success:function(response) {
						}
					});
				}
			});
        });
    </script>
@endsection
