<script type="text/javascript" src="//code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.13.0/js/mdb.min.js"></script>
<script type="text/javascript" src="//unpkg.com/sweetalert/dist/sweetalert.min.js" defer></script>

<?php 


$frontendCommonjs =  plugin_dir_url(__FILE__) . "/includes/js/dap_member_frontend_common.js?v=".rand(10,1000);  
$frontendGroupjs =  plugin_dir_url(__FILE__) . "/includes/js/dap_group_account.js?v=".rand(10,1000);  

$admin_url = admin_url('admin-ajax.php'); 
 
?> 

<script src="<?= $frontendCommonjs; ?>" type="text/javascript"></script>
<script src="<?= $frontendGroupjs; ?>" type="text/javascript"></script>

<?php 
//echo $groupId;
$data = DAP_MemberPages::loadById($groupId);

//echo "<pre>"; print_r($data);


	if(isset($data)){
		$manageGroupTemplate = $data->getTemplateHtml();	
		$template = $data->getTemplate();	

		$manageGroupTemplate = explode('||' , $manageGroupTemplate);

		$templateTableHtml = stripslashes($manageGroupTemplate[0]);
		$templateTableHtml1 = stripslashes($manageGroupTemplate[0]);
		$tableData = stripslashes($manageGroupTemplate[1]);
		$addButton = stripslashes($manageGroupTemplate[3]);
		$popupHtml = stripslashes($manageGroupTemplate[4]);
		$bulkHtml = stripslashes($manageGroupTemplate[5]);

	}	

	$success_msg = 'Added Successfully!';
	$success_msg_obj = DAP_MemberPagesValues::loadByActionIdAndName($id,'success_added_msg');
	if($success_msg_obj != '' && $success_msg_obj != false){
		$success_msg =  $success_msg_obj->getValue();	
	}
	
	$limit_reached = 'Sorry, max account limit reached!';
	$limit_reached_obj = DAP_MemberPagesValues::loadByActionIdAndName($id,'limit_reached_msg');
	if($limit_reached_obj != '' && $limit_reached_obj != false){
		$limit_reached =  $limit_reached_obj->getValue();	
	}
	
	$delete_confirmation = 'Are you sure you want to delete user?';
	$delete_confirmation_obj = DAP_MemberPagesValues::loadByActionIdAndName($id,'delete_confirm_msg');
	if($delete_confirmation_obj != '' && $delete_confirmation_obj != false){
		$delete_confirmation =  $delete_confirmation_obj->getValue();	
	}
	
	
	$delete_success = 'Deleted Successfully!';
	$delete_success_obj = DAP_MemberPagesValues::loadByActionIdAndName($id,'deleted_msg');
	if($delete_success_obj != '' && $delete_success_obj != false){
		$delete_success =  $delete_success_obj->getValue();	
	}
	
	$not_logged_in = 'Sorry, you need to be logged-in to access this page.';
	$not_logged_in_obj = DAP_MemberPagesValues::loadByActionIdAndName($id,'not_logged_in');
	if($not_logged_in_obj != '' && $not_logged_in_obj != false){
		$not_logged_in =  $not_logged_in_obj->getValue();	
	}
	
	$no_access = 'Sorry, your account does not have access to this page. This page is only available to group account owners.';
	$no_access_obj = DAP_MemberPagesValues::loadByActionIdAndName($id,'no_access');
	if($no_access_obj != '' && $no_access_obj != false){
		$no_access =  $no_access_obj->getValue();	
	}

	$bulkNoAddUserMsg = 'You need to add at least one user.';
	$bulkNoAddUserMsg_obj = DAP_MemberPagesValues::loadByActionIdAndName($id,'bulkNoAddUserMsg');
	if($bulkNoAddUserMsg_obj != '' && $bulkNoAddUserMsg_obj != false){
		$bulkNoAddUserMsg =  $bulkNoAddUserMsg_obj->getValue();	
	}

	$no_field_select_msg = 'Please select the field name';
	$no_field_select_msg_obj = DAP_MemberPagesValues::loadByActionIdAndName($id,'no_field_select_msg');
	if($no_field_select_msg_obj != '' && $no_field_select_msg_obj != false){
		$no_field_select_msg =  $no_field_select_msg_obj->getValue();	
	}

	$limit_reached_bulk = 'Added %%USERS%%. Could not add all the users as max limit was reached';
	$limit_reached_bulk_obj = DAP_MemberPagesValues::loadByActionIdAndName($id,'limit_reached_bulk');
	if($limit_reached_bulk_obj != '' && $limit_reached_bulk_obj != false){
		$limit_reached_bulk =  $limit_reached_bulk_obj->getValue();	
	}

	
	//$templateHtml = do_shortcode(dap_clean_shortcode_content($templateHtml));		
	$templateHtml = '';		


	$session = Dap_Session::getSession();
	$user = $session->getUser();
	if($adminemail==''){
		$adminemail = Dap_Config::get("ADMIN_EMAIL");
	}
	
	if($companyname=='')	{
		$companyname = Dap_Config::get("SITE_URL_DAP"); 
	}
	
	$frontendCommoncss =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/dap_member_frontend_common.css";
	echo '<link rel="stylesheet" type="text/css" href="' . $frontendCommoncss . '" />';
	
	if( !Dap_Session::isLoggedIn() || !isset($user) ) {
		//logToFile("Not logged in, returning errmsgtemplate");
		echo stripslashes($not_logged_in);
		return;
	}

	$userId = $user->getId();
	

	$parentProductsList = Dap_User::loadUsersGroupMembershipProductById($userId);
	$blogpath= get_option("siteurl");



	$bootstrapmin4css =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/bootstrap4.min.css";   
	$frontendcss =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/groupmanagement.css";   
	 
	 
	$customcss= get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/css/dap_group_account.css";
	$fcss = parse_url($customcss);
	$customcss=$fcss["path"];

	// logToFile("DAP-ShortCodes-Transactions: formcss= ". $formcss); 


	if(file_exists($fullcustomcss)) {
		$formcss=$customcss;
		//logToFile("DAP-ShortCodes-Transactions: custom css: ". $customcss);
	}

	 

	$templateHtml .= '<link rel="stylesheet" type="text/css" href="' . $frontendcss . '" />';
	$templateHtml .= '<link rel="stylesheet" type="text/css" href="' . $bootstrapmin4css . '" />';
	$templateHtml .= '<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">';
	$templateHtml .= '<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">';
	$templateHtml .= '<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">';
	$templateHtml .= '<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.13.0/css/mdb.min.css" rel="stylesheet">';

	
	if(count($parentProductsList) <= 0){
		echo stripslashes($no_access);	
	}
	
	$showData = 'N';

	foreach ($parentProductsList as $data) {
		$html = '';
		$finalHtml = '';
		$noProHtml = '';
		$templateTableHtmlNew = '';
		$displayModal = '';
		
		if(isset($data)){
			
			$productDetails = Dap_Product::loadProduct($data['product_id']);
			
			if(isset($productDetails)){
				$type = $productDetails->getAccountType();	
				
				if($type != 'group_membership'){
					$noProHtml = 'Sorry, you do not have access to any group membership products.';
					continue;	
				}
			}
			
			
			$userProductsList = Dap_User::loadUsersByParentAndProductId($data['user_id'], $data['product_id']);
			
				
			$seatsDetails = DAP_UserGroupAccount::loadByUserAndProductID($data['user_id'], $data['product_id']);
			if(count($seatsDetails) == 0){
				$max_seats = $productDetails->getMaxCount();
				$createGroupAcc = new DAP_UserGroupAccount();
				$createGroupAcc->setUserId($data['user_id']);
				$createGroupAcc->setProductId($data['product_id']);
				$createGroupAcc->setSeats($max_seats);
				$createGroupAcc->setTotalCreated(0);
				$createGroupAcc->create();

				$seatsDetails = DAP_UserGroupAccount::loadByUserAndProductID($data['user_id'], $data['product_id']);
			}
			$seats = 0;
			$total_created = 0;
			if(isset($seatsDetails)){
				$seats = $seatsDetails[0]['seats'];	
				$total_created = $seatsDetails[0]['total_created'];	
				if($seatsDetails[0]['seats'] == ''){
					$seats = 0;
				}
				if($seatsDetails[0]['total_created'] == ''){
					$total_created = 0;
				}
			}
			if($seats == '' || $seats == 0){
				continue;	
			}
			$groupRules = Dap_GroupRules::loadByProductId($data['product_id']);
			
			if(count($groupRules) > 0){
				
				foreach($groupRules as $rules){
						
						$productIds = $rules->getAllowedProductsId();
						
						$productIds = explode(',' , $productIds);
						
						$productData = Dap_Product::loadProduct($data['product_id']);
						
						$productList[$data['product_id']] =  '<select class="form-control productListDropDown" id="productDropDown_'.$data['product_id'].'" style="display:none" >';
						/*if(isset($productData)){
							$productList[$data['product_id']] .=  '<option value="'.$data['product_id'].'">'.$productData->getName().'</option>';
						}*/
						$oldProductList = array();
						foreach($productIds as $id){
							
							$newProductList = Dap_User::loadUsersByParentAndProductId($data['user_id'], $id);
							
							$productData = Dap_Product::loadProduct($id);
							if(isset($productData)){
								$productList[$data['product_id']] .=  '<option value="'.$id.'">'.$productData->getName().'</option>';
							}	
							
							$oldProductList = array_merge($oldProductList, $newProductList);
							
						}
						$productList[$data['product_id']] .=  '</select>';
						$userProductsList = $oldProductList;
					
					
					//	$templateHtml .= '<input type="hidden" value='.json_encode($productList[$data["product_id"]]).' id="product_details_obj'.$data['product_id'].'">';
						
						
				}
			}else{
				$productData = Dap_Product::loadProduct($data['product_id']);	
				
				$productList[$data['product_id']] =  '<select class="form-control productListDropDown" id="productDropDown_'.$data['product_id'].'" style="display:none" >';
				if(isset($productData)){
					$productList[$data['product_id']] .=  '<option value="'.$data['product_id'].'">'.$productData->getName().'</option>';
				}
				
				$oldProductList = array();
				
				$newProductList = Dap_User::loadUsersByParentAndProductId($data['user_id'], $data['product_id']);
				$oldProductList = $newProductList;
				
				$productList[$data['product_id']] .=  '</select>';
				$userProductsList = $oldProductList;
			}
			
			$product_name = $data['product_name'];
		
			//$buttonHtml = '<div data-id="'.$userId.'" data-key="'.$data['product_id'].'" >'.$addButton.'</div>';
			
			foreach($userProductsList as $list){
			   if($list['group_product_id'] != $data['product_id']){continue;}
				$userListByProd[$data['product_id']][] = $list['email'];
				$pId = $list['product_id'];
				$productData = Dap_Product::loadProduct($pId);	
				
				if(isset($productData)){
					$productName = $productData->getName();	
				}
			
				$html .= $tableData; 	
				$html = str_replace( '[ROWPRODUCTID]', $data['product_id'], $html);
				$html = str_replace( '[ROWUSERID]', $list['id'], $html);
				$html = str_replace( '[FIRST_NAME]', $list['first_name'].' '.$list['last_name'], $html);
				$html = str_replace( '[LAST_NAME]', $list['last_name'], $html);
				$html = str_replace( '[EMAIL]', $list['email'], $html);
				$html = str_replace( '[USERPRODUCTNAME]', $productName, $html);
			}

			
			if(count($userProductsList) == 0){
				$html = '<tr><td  colspan="4">No data found</td></tr>';
			}
			$finalHtml .= $html;
		
			
			//$finalHtml .=  DapMemberShowLoader(); 

			foreach($productList as $list){
				$productHtml .= $list;
			}

			$bulkHtml = str_replace( '[PRODUCTDROPDOWN]', $productHtml, $bulkHtml);
			
		
			$templateTableHtmlNew = str_replace( '[GROUPTABLEDATA]', $finalHtml, $templateTableHtml);
			$templateTableHtmlNew = str_replace( '[BULK_IMPORT_HTML]', $bulkHtml, $templateTableHtmlNew);
			$templateTableHtmlNew = str_replace( '[PRODUCTNAME]', $product_name , $templateTableHtmlNew);
			$templateTableHtmlNew = str_replace( '[TOTALSEATS]', $seats, $templateTableHtmlNew);
			$templateTableHtmlNew = str_replace( '[USEDSEATS]', $total_created, $templateTableHtmlNew);
		
		    	
			
			$remainigseats = $seats - $total_created;
			
			$templateTableHtmlNew = str_replace( '[REMAININGSEATS]', $remainigseats, $templateTableHtmlNew);
			$templateTableHtmlNew = $templateTableHtmlNew;
			
			$finalHtml = '';
			$html = '';
		    $showData = 'Y';	
		}
        
		
		$templateTableHtmlNew .= '<input type="hidden" name="subaccounUserId" value="'.$userId.'">';
		
		
		
		$templateHtml .= '<div data-id="'.$data['product_id'].'" class="subaccountMainOuter" style="padding: 10px;">'.$templateTableHtmlNew.'</div>';
	
	
	}
	
	if($showData == 'N'){
		$displayModal = 'display:none';
		$templateHtml = $noProHtml;	
	}
	$productUserField = '<input type="hidden" value='. json_encode($userListByProd).' id="productUserField">	';	
	
	//	echo $templateHtml;die;
	
	echo '<div class="dapGroupMembershipOuter">'.$productUserField.$templateHtml.'<input type="hidden" class="displayed_modal" value="0"></div>';
	

	
	?>
	<div class="modal fade" style="<?= $displayModal ?>" id="modalRegisterForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
	aria-hidden="true">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>

				<div class="modal-body mx-3">
					<?php 
					$alreadyAdded = array();
					foreach($productList as $key => $value){
						$productHtml .= $value;
					}
					$popupHtml = str_replace( '[PRODUCTDROPDOWN]', $productHtml, $popupHtml);
					echo '<div id="dap_member_subaccount_outer">'.$popupHtml.'</div>';
					
					echo '<input type="hidden" class="dap_user_id">';
					
					?>

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

	<div class="text-center">
		<a href="" style="display:none" class="btn btn-default btn-rounded mb-4 modalAddNewUser" data-toggle="modal" data-target="#modalRegisterForm">Launch
		Modal Register Form</a>
	</div>
 
 
<script>

	 var admin_ajaxurl = "<?= $admin_url ?>";
	 var success_msg = "<?= $success_msg ?>";
	 var limit_reached = "<?= $limit_reached ?>";
	 var delete_confirmation = "<?= $delete_confirmation ?>";
	 var delete_success = "<?= $delete_success ?>";
	 var bulkNoAddUserMsg = "<?= $bulkNoAddUserMsg ?>";
	 var no_field_select_msg = "<?= $no_field_select_msg ?>";
	 var limit_reached_bulk = "<?= $limit_reached_bulk ?>";
	 
</script>
 
 
  
  
