@yield('title', lang('usermodel.list'))

@section('breadcrumb')
	<h2>@lang('usermodel.list')</h2>
	@if($this->hasCreateRole)
		<h3><a href="{{ route('create') }}">@lang('master.add_bt')</a></h3>
	@endif
@endsection

@extension('message')

@php
	$extensionOption = [
		'name' => 'table-user',
		'title' => 'Người dùng',
		'controller_url' => route('index'),
		'custom_db_query' => function($model, $fields) {
			$match = [];
			$auth = load_auth();
			$user = $auth->getUser();
			$viewAllBranch = $auth->hasRole(\RoleGlobal::$role->viewAllBranch);


			$coll = $model->getCollection();
			$users = $coll->aggregate([
				[
					'$match' => [
						($viewAllBranch ? 'storeID' : 'branchID') => ($viewAllBranch ? $user->storeID : $user->branchID)
					]
				], 
				[
					'$addFields' => [
						'staffIdoid' => [
							'$toObjectId' => '$staffId'
						]
					]
				], 
				[
					'$lookup' => [
						'from' => 'Staffs',
						'localField' => 'staffIdoid',
						'foreignField' => '_id',
						'as' => 'jbt_Staffs'
					]
				], 
				[
					'$addFields' => [
						'groupIdoid' => [
							'$toObjectId' => '$groupId'
						]
					]
				], 
				[
					'$lookup' => [
						'from' => 'GroupUsers',
						'localField' => 'groupIdoid',
						'foreignField' => '_id',
						'as' => 'jbt_GroupUsers'
					]
				]
			])->toArray();

			
			$_users = [];
			foreach($users as $userInfo) {
				$_info = [];
				if(empty($userInfo["jbt_Staffs"]) || !count($userInfo["jbt_Staffs"]))
					continue;

				if(empty($userInfo['jbt_GroupUsers']) || !count($userInfo["jbt_GroupUsers"]))
					continue;

				$_info['Staffs_name'] = $userInfo["jbt_Staffs"][0]['name'];
				$_info['GroupUsers_name'] = $userInfo["jbt_GroupUsers"][0]['name'];
				$_info['id'] = $userInfo['_id'];
				$_info['name'] = $userInfo['name'];
				$_info['username'] = $userInfo['username'];
				
				
				$_users[] = $_info;
			}

			return $_users;
			
		}
	];
@endphp

@extension('datatable', 'UserModel', $extensionOption)