<?php $this->include('rs/utils.php')?>
 <?= $this->extend('rs/template-user', $data); ?>

 <?= $this->section('content'); ?>

<style>
	.icon-btn
	{
		display:inline-block;
		width:36px;
		height: 36px;
		border-radius: 50%;
		border: 1px solid #ccc;
	}
	.actions-menu
	{
		display:block!important;		
	}
	
	.filter-item
	{
		display:inline-block!important;	
		line-height:40px!important;
	}
	input{border:1px solid #aaa!important}
	label {width:70px!important;text-align:right!important;}
	
	.pull-left{
		float: left !important;
		}
		
	@media screen and (max-width:900px) 
	{
		.priority-2{display:none;}
		
	}
	
	
</style>

  <div class="card shadow mb-4">

   <div class="card-header  justify-content-between align-items-center">                               

    <h4 class="card-title">Users</h4> 

   </div>

   <div class="card-body">
	<ul class="nav nav-tabs">
		<li class="nav-item">
			<a class="nav-link active role-tab border-left-primary shadow" data-role="All" href="#">All Users</a>
		</li>
		<li class="nav-item" style="background-color: <?= (isset($new_users) && $new_users > 0) ? '#ffb3b3' : '' ?>">
			<a class="nav-link role-tab" data-role="New" href="#">New Users</a>
		</li>
		<li class="nav-item">
			<a class="nav-link role-tab" data-role="Seller" href="#">Sellers</a>
		</li>
		<li class="nav-item">
			<a class="nav-link role-tab" data-role="Buyer" href="#">Buyers</a>
		</li>
		<li class="nav-item">
			<a class="nav-link role-tab" data-role="Admin" href="#">Developers</a>
		</li>
	</ul>
    <table class="table table-sm  small" id="dataTableLarge"  "paging"="false" width="99%" cellspacing="0">
				
    
        <thead>

          <tr>
			<th>id</th>
			<th>Company</th>
			<th>Country</th>
			<th>Contact</th>
            <th>Email</th>
			<th>Created</th>
		    <th>Access level</th>
			<th>Edit</th>
          </tr>

        </thead>
		<tbody id="users-table">
		<?php if(isset($users)){ 
			$i=0;
			$style="";
			foreach($users as $items)
			{
			
			if($items['active']==1)	
				$style="style='color:#0026FF'";
			if($items['isadmin']==1)
				$style="style='font-weight:700;color:#000'";
			if($items['active']==0)
				$style="style='color:#FF0000'";
			switch($items['access'])
			{
				case 0: $access='Blocked (No access)';break;
				case 1: $access='Read-only Seller';break;
				case 2: $access='Read-only Buyer';break;
				case 3: $access='Read-only Seller & Buyer';break;
				case 4: $access='Read-Write Seller';break;
				case 5: $access='Read-Write Buyer';break;
				case 6: $access='Read-Write Seller & Buyer';break;
			}
			?>
			<tr <?=$style?>>
				<td><?php echo $items['id']; ?></td>
			    <td><?php echo $items['companyname']; ?></td>
				<td><?php echo $items['country']; ?></td>
				<td><?php echo $items['firstname'].' '.$items['lastname']; ?></td>
				<td><?php echo $items['email']; ?></td>
				<td><?php echo $items['created_at']; ?></td>  					
				<td><?php echo $access; ?></td>
				<td class="priority-2"><a href="<?php echo site_url('/edituser/'.$items['id']);?>"  title="Editeaza" class="btn btn-outline-success btn-sm"><i class="fas fa-fw fa-edit"></i></a></td>
				</tr>
				<?php $i++ ?>
				
			<?php } ?>
		<?php }?>

    </table>

    <script type="text/javascript">

     $(document).ready(function() {
		
		$('#dataTableLarge').DataTable({paging: false, 
		layout: {
			top: 'info',
			topStart: 'search',
			topEnd: 'info'
		}
		
		});
		
		
		
		//Move the search box
		var rows = $('#dataTableLarge_wrapper').children('.row');
		row0=rows[0];
		var kids1 = row0.children;
		var len = kids1.length;
		
		if(len>1)
		{
			kids1[0].style.display = "none";
		}
		
		$('#dataTableLarge_filter').addClass('pull-left');
		$('#dataTableLarge_filter input').css('width', '260px');
		$('#dataTableLarge_filter').css('margin-top', '5px');
		($("#dataTableLarge_filter" ).parent()).append( "<div style='float:right;'><?php echo count($users);?> randuri</div>");
		
		document.querySelectorAll('.role-tab').forEach(tab => {
			tab.addEventListener('click', function (e) {
				e.preventDefault();
				
				// Remove active class from all tabs
				document.querySelectorAll('.nav-link').forEach(link => link.classList.remove('active','border-left-primary','shadow'));
				
				// Add active class to the clicked tab
				this.classList.add('active', 'border-left-primary', 'shadow');
				
				// Get the role from the data attribute
				const role = this.getAttribute('data-role');
				
				// Fetch users for the selected role
				fetchUsers(role);
			});
		});	
	});
	
	function fetchUsers(role) {
		$.ajax({
			url: `/getusers/${role}`,
			method: 'GET',
			contentType: 'application/json',
			success: function (data) {
				const usersTable = document.getElementById('users-table');
				usersTable.innerHTML = ''; // Clear existing rows

				// Destroy the existing DataTable instance
				if ($.fn.DataTable.isDataTable('#dataTableLarge')) {
					$('#dataTableLarge').DataTable().clear().destroy();
				}

				// Append new rows to the table
				data.users.forEach(user => {
					let row = `
					<tr style="${getRowStyle(user)}">
						<td>${user.id}</td>
						<td>${user.companyname}</td>
						<td>${user.country}</td>
						<td>${user.firstname} ${user.lastname}</td>
						<td>${user.email}</td>
						<td>${user.created_at}</td>
						<td>${getAccessLevel(user.access)}</td>
						<td class="priority-2">
							<a href="/edituser/${user.id}" title="Edit" class="btn btn-outline-success btn-sm">
								<i class="fas fa-fw fa-edit"></i>
							</a>
						</td>
					</tr>`;
					usersTable.innerHTML += row;
				});

				// Reinitialize the DataTable
				$('#dataTableLarge').DataTable({
					paging: false,
					layout: {
						top: 'info',
						topStart: 'search',
						topEnd: 'info',
					},
				});

				// Move the search box again
				const rows = $('#dataTableLarge_wrapper').children('.row');
				if (rows.length > 0 && rows[0].children.length > 1) {
					rows[0].children[0].style.display = 'none';
				}

				$('#dataTableLarge_filter').addClass('pull-left');
				$('#dataTableLarge_filter input').css('width', '260px');
				$('#dataTableLarge_filter').css('margin-top', '5px');
				$('#dataTableLarge_filter')
					.parent()
					.append(`<div style='float:right;'>${data.count} randuri</div>`);
			},
			error: function (xhr, status, error) {
				console.error('Error fetching users:', error);
			},
		});
	}

	function popup(url) {
		
		window.location.href = url;
        //newwindow=window.open(url,'quicktransfer','popup=1,height=300,width=450,directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,top=100,left=100,resizable = no');
        //if (window.focus) {newwindow.focus()}
        return false;
    }
	
	function _______popup(url) {
        newwindow=window.open(url,'quicktransfer','popup=1,height=300,width=450,directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,top=100,left=100,resizable = no');
        if (window.focus) {newwindow.focus()}
        return false;
    }



	function getRowStyle(user) {
		var style = "";
		if (user.active == 1) style= "color:#0026FF";
		if (user.isadmin == 1) style= "font-weight:700;color:#000";
		if (user.active == 0) style= "color:#FF0000";
		return style;
	}

	function getAccessLevel(access) {
		const levels = {
			0: 'Blocked (No access)',
			1: 'Read-only Seller',
			2: 'Read-only Buyer',
			3: 'Read-only Seller & Buyer',
			4: 'Read-Write Seller',
			5: 'Read-Write Buyer',
			6: 'Read-Write Seller & Buyer',
		};
		return levels[access] || 'Unknown';
	}


    </script>

    <!-- <script type="text/javascript">document.getElementById("inventory").classList.add("active");</script> -->
	

   

    <?= $this->endsection(); ?>       

