<?php

namespace App\Http\Controllers;

use Auth;
use DB;
use App\Models\Journal;
use App\Models\Ebook;
use App\Models\Volume;
use App\Models\EbookVolume;
use App\Models\Issue;
use App\Models\Article;
use App\Models\Chapter;
use App\Models\ContentAccess;
use App\Models\BookAccess;
use App\Models\Disease;
use App\Models\UserAccess\UserAccess;
use App\Models\UserAccess\UserAccessRequest;
use App\Models\UserAccess\UserAccessOrganization;
use App\Models\UserAccess\UserAccessIpRange;
use App\Models\Country;
use App\User;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;

class UserAccessController extends BenthamController
{

	public function user_access(Request $request, $page)
    {  
		$content=array();

		if ($request->ajx_search == true)
		{
			$param = $this->ajax_search($request);
			return $param;
		}
		
		$param = $this->param($request);
		$search = $this->frm_search($request,$page);
		
		if($page == 'view')
		{
			if($request->btn_submit == 'Delete')
			{	
				return $this->DeleteContentList($request,$param,$search);
			}
			elseif($request->btn_delete_all == 'Delete_User_IP_Access')
			{	
				return $this->DeleteIPBaseContent($request,$param,$search);
			}
			elseif($request->btn_export == 'export')
			{
				return $this->ExportTokenList($request);
			}
			else
			{
				return $this->GetContentList($request,$param,$search);
			}
		}
		elseif($page == 'add')
		{
			if (!isset($request->request_id))
			{	
				return redirect('admin/useraccess/view');
			}
			elseif($request->btn_add_org == 'submit')
			{	
				$messages['organization_name.required'] = 'please enter organization name';
				$messages['country_id.required'] = 'please select country ';
				
				$validator = Validator::make($request->all(), 
				[
				  "organization_name"  	=> 'required|unique:user_access_organizations',
				  "country_id"  		=> 'required',
				],$messages);
				
				if ($validator->fails())
				{
					return View::make('admin.user_access.user_access_add',with(['param' => $param,
						'search' => $search,
						'validator' => $validator]))->withErrors($validator->errors());
				} 
				else 
				{
					if (isset($request->request_id))
					{
						$request_id = decrypt($request->request_id);
						
						$user    = Auth::user();
						$access_organization = array(
							'organization_name'      => $request->organization_name,
							'organization_website' 	 => $request->organization_website,
							'country_id'		 	 => DB::table('country')->where('iso',$request->country_id)->first()->country_id,
							'system_ip'              => ip2long($request->ip()),
							'created_on'             => time(),
							'created_by'             => $user->id,
						);

						$access_organization_id = UserAccessOrganization::AddAccessOrganization($access_organization);
						
						if (!empty($request->organization_name))
						{
							$param['organization_id'] = $access_organization_id;
							$param['org_name_search'] = $request->organization_name;
							
							$p['organization_name'] = $request->organization_name;
							$search['organization_search'] = UserAccessOrganization::GetActiveOrganizationDetails($p);
						}
					}
				}
			}
			elseif($request->btn_submit == 'submit')
			{
				return $this->SaveContentForm($request,$param,$search);
			}
			
			return $this->GetContentForm($request,$param,$search);
		}
		elseif($page == 'edit')
		{
			
			if (!isset($request->request_id))
			{
				return redirect('admin/useraccess/view');
			}
			
			if($request->btn_update == 'submit')
			{
				return $this->UpdateTokenInfo($request,$param,$search);
			}
			else
			{
				return View::make('admin.user_access.token_access_add',with(['param' => $param,
					'search' => $search,
					'content' => $content]));
			}
	
		}
		elseif($page == 'user_access_date')
		{
			if (!isset($request->request_id))
			{
				return redirect('admin/useraccess/view');
			}

			if($request->btn_update == 'submit')
			{
				return $this->UpdateUserAccessDate($request,$param,$search);
			}
			else
			{
				return View::make('admin.user_access.user_access_date_add',with(['param' => $param,
					'search' => $search,'content' => $content]));
			}	
		}
    }
	
	
	public function ajax_search($request)
	{
		$ajx_search = $request->get('ajx_search');
		
		if ($ajx_search == true)
		{
			if ($request->module == 'org_search')
			{
				$p['organization_name'] = $request->org_name_search;
				$org_search = UserAccessOrganization::GetActiveOrganizationDetails($p);
				if (!empty($org_search[0]))
				{
					return response()->json($org_search, 200);	
				}
				else
				{
					return response()->json(false, 200);	
				}
				
			}
			
			if ($request->module == 'journal')
			{
				$journal_search = Journal::GetJournalTitle();
				return response()->json($journal_search, 200);
			}
			
			if ($request->module == 'volume')
			{
				
				$param['journal_id'] = $request->get('journal_id');
				$param['content_type_id'] = 'null';
				
				$param['group'] = false;
				
				$join['journal_access'] = true;
				$join['volume'] = true;
				$volume_search = UserAccess::GetConditionalVolumes($param,$join);
				return response()->json($volume_search, 200);
			}
			
			if ($request->module == 'ebook')
			{
				$ebook_search = Ebook::GetEbookTitle();
				return response()->json($ebook_search, 200);
			}
			
			if ($request->module == 'issue')
			{
				$join['journal_access'] = true;
				$join['journal'] = true;
				$join['volume'] = true;
				$join['year'] = true;
		
				$p['journal_id'] = $request->get('journal_id');
				$p['volume_id'] = $request->get('volume_id');
				$p['content_type_id'] = 'null';
				
				$issue_list = UserAccess::GetConditionalIssues($p, $join);
				return response()->json($issue_list, 200);
			}
			
			if ($request->module == 'token')
			{
				$p['user_name'] = $request->get('user_name');
				$p['access_type'] = $request->get('access_type');
				$p['access_on'] = $request->get('access_on');
				return response()->json(UserAccess::GetTokenlimit($p), 200);
			}
		}
	}
	
	public function frm_search($request,$page)
	{				

		$search = array();
		
		// Consortia User Search
		if (!empty($request->consortia_user_name))
		{
			$user = User::where('name',$request->consortia_user_name)->first();
			
			if(!empty($user))
			{
				$param['user_id'] = $user->id;
				$order['user_access_id'] = true;
				$param['user_access_status'] = 1;
				$param['access_base_type'] = 1;
				$param['access_type_on'] = "journal_volume";
				$search['consortia'] = UserAccess::GetUserAccess($param, null, null, null, $order);	

			}
		}
		
		// Token Search
		if (!empty($request->token_search))
		{
			$p['user_name'] = $request->get('user_name');
			$p['access_type'] = $request->get('access_type_id');
			$p['access_on'] = $request->get('access_on');
			$search['token_search']  = UserAccess::GetTokenlimit($p);
		}
		
		// Organization Search
		if (!empty($request->org_name_search))
		{
			$p['organization_name'] = $request->org_name_search;
			$search['organization_search'] = UserAccessOrganization::GetActiveOrganizationDetails($p);
		}
		
		// if ($request->frm_search == true)
		// {
			if ($request->access_on == 'journal_volume' && $page == 'view')
			{
				$p['journal_id'] = $request->get('journal_id');
				
				$search['journal_search'] = Journal::GetJournalTitle();
			}
			
			if ($request->access_on == 'ebook_volume' && $page == 'view')
			{
				$p['ebook_id'] = $request->get('ebook_id');
				
				$search['ebook_search'] = Ebook::GetEbookTitle();
			}
		
			if ($request->access_on == 'issue')
			{
				$p['journal_id'] = $request->get('journal_id');
				
				$search['journal_search'] = Journal::GetJournalTitle();
				
				if (!empty($request->journal_id))
				{
					$p['journal_id'] = $request->get('journal_id');
					$search['volume_search']  = Volume::GetVolumeTitleById($p);
				}
			}

			if ($request->access_on == 'article')
			{
				
				$search['journal_search'] = Journal::GetJournalTitle();
				
				if (!empty($request->journal_id))
				{
					$p['journal_id'] = $request->get('journal_id');	
					$search['volume_search']  = Volume::GetVolumeTitleById($p);
				}
				
				$join['journal_access'] = true;
				$join['journal'] = true;
				$join['volume'] = true;
				$join['year'] = true;
		
				$p['volume_id'] = $request->get('volume_id');
				$p['content_type_id'] = 'null';
				
				if (!empty($request->volume_id))
				{
					$search['issue_search'] = UserAccess::GetConditionalIssues($p, $join);
				}
			}
			
			if ($request->access_on == 'chapter')
			{
				
				$param['content_type_id'] = 'null';
				$param['group'] = false;
				$join['ebook_access'] = true;
				$join['ebook'] = true;
				$search['ebook_volume_search'] = UserAccess::GetConditionalEbookVolumes($param,$join);
			}

			if ($request->access_on == 'disease')
			{	
				$search['disease_search'] = Disease::DiseaseParent();
				
			}
		// }
		
		//dd($search);
		
		return $search;
	}
	
	public function add_user_access_volume_user_base($request,$dup_content,$param)
	{
		$access_data = array();
		$access_insert = array();
		
		if(!empty($request->journal_volume))
		{
		
			foreach($request->journal_volume as  $journal)
			{
				$epub = 0;
				$journal = explode(',',$journal);
				$j_id = $journal[0];
				$v_id = $journal[1];

				if(isset($request->journal_epub[$j_id][$v_id]))
				{
					$epub = 1;
				}					
				
				$dup_vol = '0';
				if (!empty($dup_content))
				{
					foreach($dup_content as $dup_k => $dup_v)
					{
						if ($v_id == $dup_v->volume_id)
						{
							$dup_vol = true;
							break;
						}
					}
				}
					
				if ($dup_vol == false)
				{
					$access_data['user_access_id'] = $param['user_access_id'];
					$access_data['journal_id'] = $j_id;
					$access_data['volume_id'] = $v_id;
					$access_data['user_id'] = $param['user_id'];
					$access_data['type'] = $request->access_type_id;
					$access_data['track'] = $epub;
					
					if ($request->perpetual == 1)
					{
						$access_data['perpetual'] = $request->perpetual; 
					}
					else
					{
						$access_data['from_date'] = $request->from_date;  
						$access_data['to_date'] = $request->to_date; 
					}
					$access_data['sys_user_id'] = Auth::user()->id;
					$access_data['sys_time'] = time();
					$access_data['sys_ip'] = ip2long($request->ip());
					
					$access_insert[] = $access_data;
					unset($access_data);
				}
			}
			
			return $access_insert;
		}
	}
	
	public function add_user_access_volume_ip_base($request,$dup_content,$param)
	{
		$access_data = array();
		$access_insert = array();
		//dd($request->journal_volume);
		if(!empty($request->journal_volume))
		{
		
			foreach($request->journal_volume as  $journal)
			{
				$epub = 0;
				$journal = explode(',',$journal);
				$j_id = $journal[0];
				$v_id = $journal[1];
				
				if(isset($request->journal_epub[$j_id][$v_id]))
				{
					$epub = 1;
				}					
				
						$dup_vol = '0';
						if (!empty($dup_content))
						{
							foreach($dup_content as $b_k => $b_v)
							{
								if ($b_v->volume_id == $v_id)
								{
									$dup_vol = $v_id;
									$bound_ip['conflict_user_id'] = $b_v->user_id;
									$bound_ip['volume_id'] = $b_v->volume_id;
									$bound_ip['from_ip'] = $b_v->from_ip;
									$bound_ip['to_ip'] = $b_v->to_ip;
									$bound_ips[] = $bound_ip;
								}
							}
						}
							
						if ($dup_vol != $v_id)
						{
							foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
							{
								$access_data['user_access_id'] = $param['user_access_id'];
								$access_data['journal_id'] = $j_id;
								$access_data['volume_id'] = $v_id;
								$access_data['user_id'] = $param['user_id'];
								
								$access_data['from_ip'] = $ip_v['from_ip'];
								$access_data['to_ip'] = $ip_v['to_ip'];
								
								$access_data['type'] = $request->access_type_id;
								
								$access_data['track'] = $epub;
								
								if ($request->perpetual == 1)
								{
									$access_data['perpetual'] = $request->perpetual; 
								}
								else
								{
									$access_data['from_date'] = $request->from_date;  
									$access_data['to_date'] = $request->to_date; 
								}
								
								$access_data['sys_user_id'] = Auth::user()->id;
								$access_data['sys_time'] = time();
								$access_data['sys_ip'] = ip2long($request->ip());
								
								$access_insert[] = $access_data;
								unset($access_data);
							}	
						}
						else
						{
							
							foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
							{		
								$ip_conflict = false;
								
								if (!empty($bound_ips))
								{
									foreach($bound_ips as $b_ip_k => $b_ip_v)
									{
										if ( ($v_id == $b_ip_v['volume_id']) && ($b_ip_v['to_ip'] >= $ip_v['from_ip'] && $b_ip_v['from_ip'] <= $ip_v['to_ip']))
										{
											$ip_conflict = true;
											$conflict_ip['user'] = $request->user_name;
											$conflict_ip['journal_id'] = $j_id;
											$conflict_ip['volume_id'] = $v_id;
											$conflict_ip['user_ips'] = long2ip($ip_v['from_ip']) .' - '. long2ip($ip_v['to_ip']);
											$conflict_ip['conflict_user_id'] = $b_ip_v['conflict_user_id'];
											$conflict_ip['conflict_ips'] = long2ip($b_ip_v['from_ip']) .' - '. long2ip($b_ip_v['to_ip']);
											$conflict_ips[] = $conflict_ip;
										}
									}
								}
								
								if ($ip_conflict == false)
								{
									$access_data['user_access_id'] = $param['user_access_id'];
									$access_data['journal_id'] = $j_id;
									$access_data['volume_id'] = $v_id;
									$access_data['user_id'] = $param['user_id'];
									
									$access_data['from_ip'] = $ip_v['from_ip'];
									$access_data['to_ip'] = $ip_v['to_ip'];
									
									$access_data['type'] = $request->access_type_id;
									
									$access_data['track'] = $epub;
									
									if ($request->perpetual == 1)
									{
										$access_data['perpetual'] = $request->perpetual; 
									}
									else
									{
										$access_data['from_date'] = $request->from_date; 
										$access_data['to_date'] = $request->to_date; 
									}
									$access_data['sys_user_id'] = Auth::user()->id;
									$access_data['sys_time'] = time();
									$access_data['sys_ip'] = ip2long($request->ip());
									
									$access_insert[] = $access_data;
									
									unset($access_data);
						}
					}	
				}
			}
			
			if (!empty($conflict_ips))
			{
				$request->conflict_ips = $conflict_ips;
			}
			
			return $access_insert;
		}
	}
	
	public function add_user_access_ebook_volume_user_base($request,$dup_content,$param)
	{
		$access_data = array();
		$access_insert = array();
		
		if(!empty($request->ebook_volumes))
		{
			foreach($request->ebook_volumes as $v_id => $val)
			{
				
				$res = explode(',',$val);
				$ebook_id = $res[0];
				$ebook_volume_id = $res[1];
				
				$dup_vol = false;
				if (!empty($dup_content))
				{
					foreach($dup_content as $dup_k => $dup_v)
					{
						if ($v_id == $dup_v->volume_id)
						{
							$dup_vol = true;
							break;
						}
					}
				}
					
				if ($dup_vol == false)
				{
					$access_data['user_access_id'] = $param['user_access_id'];
					$access_data['ebook_id'] = $ebook_id;
					$access_data['volume_id'] = $ebook_volume_id;
					$access_data['user_id'] = $param['user_id'];
					$access_data['type'] = $request->access_type_id;
					
					if ($request->perpetual == 1)
					{
						$access_data['perpetual'] = $request->perpetual; 
					}
					else
					{
						$access_data['from_date'] = $request->from_date;  
						$access_data['to_date'] = $request->to_date; 
					}
					$access_data['sys_user_id'] = Auth::user()->id;
					$access_data['sys_time'] = time();
					$access_data['sys_ip'] = ip2long($request->ip());
					
					$access_insert[] = $access_data;
					unset($access_data);
				}
			}	
			return $access_insert;
		}
	}
	
	public function add_user_access_ebook_volume_ip_base($request,$dup_content,$param)
	{
		$access_data = array();
		$access_insert = array();
		
		if(!empty($request->ebook_volumes))
		{
			foreach($request->ebook_volumes as $v_id => $val)
			{
				$res = explode(',',$val);
				$ebook_id = $res[0];
				$ebook_volume_id = $res[1];
				
				$dup_vol = '0';
				if (!empty($dup_content))
				{
					foreach($dup_content as $b_k => $b_v)
					{
						if ($b_v->volume_id == $ebook_volume_id)
						{
							$dup_vol = $ebook_volume_id;
							$bound_ip['conflict_user_id'] = $b_v->user_id;
							$bound_ip['volume_id'] = $b_v->volume_id;
							$bound_ip['from_ip'] = $b_v->from_ip;
							$bound_ip['to_ip'] = $b_v->to_ip;
							$bound_ips[] = $bound_ip;
						}
					}
				}
					
				if ($dup_vol != $ebook_volume_id)
				{
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{
						$access_data['user_access_id'] = $param['user_access_id'];
						$access_data['volume_id'] = $ebook_volume_id;
						$access_data['ebook_id'] = $ebook_id;
						$access_data['user_id'] = $param['user_id'];
						
						$access_data['from_ip'] = $ip_v['from_ip'];
						$access_data['to_ip'] = $ip_v['to_ip'];
						
						$access_data['type'] = $request->access_type_id;
						
						
						if ($request->perpetual == 1)
						{
							$access_data['perpetual'] = $request->perpetual; 
						}
						else
						{
							$access_data['from_date'] = $request->from_date;  
							$access_data['to_date'] = $request->to_date; 
						}
						
						$access_data['sys_user_id'] = Auth::user()->id;
						$access_data['sys_time'] = time();
						$access_data['sys_ip'] = ip2long($request->ip());
						
						$access_insert[] = $access_data;
						unset($access_data);
					}	
				}
				else
				{
					
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{		
						$ip_conflict = false;
						
						if (!empty($bound_ips))
						{
							foreach($bound_ips as $b_ip_k => $b_ip_v)
							{
								if ( ($ebook_volume_id == $b_ip_v['volume_id']) && ($b_ip_v['to_ip'] >= $ip_v['from_ip'] && $b_ip_v['from_ip'] <= $ip_v['to_ip']))
								{
									$ip_conflict = true;
									$conflict_ip['user'] = $request->user_name;
									$conflict_ip['ebook_id'] = $ebook_id;
									$conflict_ip['volume_id'] = $b_ip_v['volume_id'];
									$conflict_ip['user_ips'] = long2ip($ip_v['from_ip']) .' - '. long2ip($ip_v['to_ip']);
									$conflict_ip['conflict_user_id'] = $b_ip_v['conflict_user_id'];
									$conflict_ip['conflict_ips'] = long2ip($b_ip_v['from_ip']) .' - '. long2ip($b_ip_v['to_ip']);
									$conflict_ips[] = $conflict_ip;
								}
							}
						}
						
						if ($ip_conflict == false)
						{
							$access_data['user_access_id'] = $param['user_access_id'];
							$access_data['ebook_id'] = $ebook_id;
							$access_data['volume_id'] = $ebook_volume_id;
							$access_data['user_id'] = $param['user_id'];
							$access_data['from_ip'] = $ip_v['from_ip'];
							$access_data['to_ip'] = $ip_v['to_ip'];
							$access_data['type'] = $request->access_type_id;
							
							if ($request->perpetual == 1)
							{
								$access_data['perpetual'] = $request->perpetual; 
							}
							else
							{
								$access_data['from_date'] = $request->from_date;  
								$access_data['to_date'] = $request->to_date; 
							}
							$access_data['sys_user_id'] = Auth::user()->id;
							$access_data['sys_time'] = time();
							$access_data['sys_ip'] = ip2long($request->ip());
							
							$access_insert[] = $access_data;
							
							unset($access_data);
						}
					}
				}
			}	
			
			if (!empty($conflict_ips))
			{
				$request->conflict_ips = $conflict_ips;
			}
			
			return $access_insert;
		}
	}
	
	public function add_user_access_issue_user_base($request,$dup_content,$param)
	{
		
		$access_data = array();
		$user_access_insert = array();
		
		if(!empty($request->issue))
		{
			foreach($request->issue as $k => $v)
			{
				$vals = explode(',',$v);
			
				$journal_id = $vals[0];
				$volume_id = $vals[1];
				$issue_id = $vals[2];	
				
				$dup_vol = false;
				if (!empty($dup_content))
				{
					foreach($dup_content as $dup_k => $dup_v)
					{
						if ($issue_id == $dup_v->issue_id)
						{
							$dup_vol = true;break;
						}
					}
				}
					
				if ($dup_vol == false)
				{
					$access_data['user_access_id'] = $param['user_access_id'];
					$access_data['journal_id'] = $journal_id;
					$access_data['volume_id'] = $volume_id;
					$access_data['issue_id'] = $issue_id;
					$access_data['user_id'] = $param['user_id'];
					$access_data['type'] = $request->access_type_id;
					
					if ($request->perpetual == 1)
					{
						$access_data['perpetual'] = $request->perpetual; 
					}
					else
					{
						$access_data['from_date'] = $request->from_date;  
						$access_data['to_date'] = $request->to_date; 
					}
					$access_data['sys_user_id'] = Auth::user()->id;
					$access_data['sys_time'] = time();
					$access_data['sys_ip'] = ip2long($request->ip());
					
					$user_access_insert[] = $access_data;
					unset($access_data);
				}
			}
			return $user_access_insert;	
		}
	}
	
	public function add_user_access_issue_ip_base($request,$dup_content,$param)
	{
		$access_data = array();
		$user_access_insert = array();
		
		if(!empty($request->issue))
		{
			foreach($request->issue as $k => $v)
			{
				$vals = explode(',',$v);
			
				$journal_id = $vals[0];
				$volume_id = $vals[1];
				$issue_id = $vals[2];	
				$dup_issue = '0';
				
				if (!empty($dup_content))
				{
					foreach($dup_content as $b_k => $b_v)
					{
						if ($b_v->issue_id == $issue_id)
						{
							$dup_issue = $issue_id;
							$bound_ip['conflict_user_id'] = $b_v->user_id;
							$bound_ip['volume_id'] = $b_v->volume_id;
							$bound_ip['issue_id'] = $b_v->issue_id;
							$bound_ip['from_ip'] = $b_v->from_ip;
							$bound_ip['to_ip'] = $b_v->to_ip;
							$bound_ips[] = $bound_ip;
						}
					}
				}
				
				if ($dup_issue != $issue_id)
				{
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{
						$access_data['user_access_id'] = $param['user_access_id'];
						$access_data['journal_id'] = $journal_id;
						$access_data['volume_id'] = $volume_id;
						$access_data['issue_id'] = $issue_id;
						
						$access_data['user_id'] = $param['user_id'];
						
						$access_data['from_ip'] = $ip_v['from_ip'];
						$access_data['to_ip'] = $ip_v['to_ip'];
						
						$access_data['type'] = $request->access_type_id;
						
						
						
						if ($request->perpetual == 1)
						{
							$access_data['perpetual'] = $request->perpetual; 
						}
						else
						{
							$access_data['from_date'] = $request->from_date;  
							$access_data['to_date'] = $request->to_date; 
						}
						$access_data['sys_user_id'] = Auth::user()->id;
						$access_data['sys_time'] = time();
						$access_data['sys_ip'] = ip2long($request->ip());
						
						$user_access_insert[] = $access_data;
						
						unset($access_data);
					}	
					
				}
				else
				{
					
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{		
						$ip_conflict = false;
						
						if (!empty($bound_ips))
						{
							foreach($bound_ips as $b_ip_k => $b_ip_v)
							{
								if ( ($issue_id == $b_ip_v['issue_id']) && ($b_ip_v['to_ip'] >= $ip_v['from_ip'] && $b_ip_v['from_ip'] <= $ip_v['to_ip']))
								{
									$ip_conflict = true;
									$conflict_ip['user'] = $request->user_name;
									$conflict_ip['journal_id'] = $journal_id;
									$conflict_ip['volume_id'] = $volume_id;
									$conflict_ip['issue_id'] = $issue_id;
									$conflict_ip['user_ips'] = long2ip($ip_v['from_ip']) .' - '. long2ip($ip_v['to_ip']);
									$conflict_ip['conflict_user_id'] = $b_ip_v['conflict_user_id'];
									$conflict_ip['conflict_ips'] = long2ip($b_ip_v['from_ip']) .' - '. long2ip($b_ip_v['to_ip']);
									$conflict_ips[] = $conflict_ip;
								}
							}
						}
						
						if ($ip_conflict == false)
						{
							$access_data['user_access_id'] = $param['user_access_id'];
							$access_data['journal_id'] = $journal_id;
							$access_data['volume_id'] = $volume_id;
							$access_data['issue_id'] = $issue_id;
							$access_data['user_id'] = $param['user_id'];
							
							$access_data['from_ip'] = $ip_v['from_ip'];
							$access_data['to_ip'] = $ip_v['to_ip'];
							
							$access_data['type'] = $request->access_type_id;
							
							
							
							if ($request->perpetual == 1)
							{
								$access_data['perpetual'] = $request->perpetual; 
							}
							else
							{
								$access_data['from_date'] = $request->from_date;  
								$access_data['to_date'] = $request->to_date; 
							}
							$access_data['sys_user_id'] = Auth::user()->id;
							$access_data['sys_time'] = time();
							$access_data['sys_ip'] = ip2long($request->ip());
							
							$user_access_insert[] = $access_data;
							
							unset($access_data);
						}
					}
				}
			}
			
			
			if (!empty($conflict_ips))
			{
				$request->conflict_ips = $conflict_ips;
			}
			
			return $user_access_insert;
		}
	}
	
	public function add_user_access_article_user_base($request,$dup_content,$param)
	{
		$access_data = array();
		$user_access_insert = array();
		
		if(!empty($request->article))
		{
		
			foreach($request->article as $k => $v)
			{
				$vals = explode(',',$v);
			
				$journal_id = $vals[0];
				$volume_id = $vals[1];
				$issue_id = $vals[2];	
				$article_id = $vals[3];	
				
				$dup_vol = false;
				if (!empty($dup_content))
				{
					foreach($dup_content as $dup_k => $dup_v)
					{
						if ($article_id == $dup_v->article_id)
						{
							$dup_vol = true;break;
						}
					}
				}
					
				if ($dup_vol == false)
				{
					$access_data['user_access_id'] = $param['user_access_id'];
					$access_data['journal_id'] = $journal_id;
					$access_data['volume_id'] = $volume_id;
					$access_data['issue_id'] = $issue_id;
					$access_data['article_id'] = $article_id;
					$access_data['user_id'] = $param['user_id'];
					$access_data['type'] = $request->access_type_id;
					
					if ($request->perpetual == 1)
					{
						$access_data['perpetual'] = $request->perpetual; 
					}
					else
					{
						$access_data['from_date'] = $request->from_date;  
						$access_data['to_date'] = $request->to_date; 
					}
					$access_data['sys_user_id'] = Auth::user()->id;
					$access_data['sys_time'] = time();
					$access_data['sys_ip'] = ip2long($request->ip());
					
					$user_access_insert[] = $access_data;
					unset($access_data);
				}
			}
			return $user_access_insert;
		}
	}
	
	public function add_user_access_article_ip_base($request,$dup_content,$param)
	{
		
		$access_data = array();
		$user_access_insert = array();
		
		if(!empty($request->article))
		{
			foreach($request->article as $k => $v)
			{
				$vals = explode(',',$v);
			
				$journal_id = $vals[0];
				$volume_id = $vals[1];
				$issue_id = $vals[2];	
				$article_id = $vals[3];	
				
				$dup_article = '0';
				
				if (!empty($dup_content))
				{
					foreach($dup_content as $b_k => $b_v)
					{
						if ($b_v->article_id == $article_id)
						{
							$dup_article = $article_id;
							$bound_ip['conflict_user_id'] = $b_v->user_id;
							$bound_ip['volume_id'] = $b_v->volume_id;
							$bound_ip['issue_id'] = $b_v->issue_id;
							$bound_ip['article_id'] = $b_v->article_id;
							$bound_ip['from_ip'] = $b_v->from_ip;
							$bound_ip['to_ip'] = $b_v->to_ip;
							$bound_ips[] = $bound_ip;
						}
					}
				}
					
				if ($dup_article != $article_id)
				{
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{
						$access_data['user_access_id'] = $param['user_access_id'];
						$access_data['journal_id'] = $journal_id;
						$access_data['volume_id'] = $volume_id;
						$access_data['issue_id'] = $issue_id;
						$access_data['article_id'] = $article_id;
						
						$access_data['user_id'] = $param['user_id'];
						
						$access_data['from_ip'] = $ip_v['from_ip'];
						$access_data['to_ip'] = $ip_v['to_ip'];
						
						$access_data['type'] = $request->access_type_id;
						
						
						
						if ($request->perpetual == 1)
						{
							$access_data['perpetual'] = $request->perpetual; 
						}
						else
						{
							$access_data['from_date'] = $request->from_date;  
							$access_data['to_date'] = $request->to_date; 
						}
						
						$access_data['sys_user_id'] = Auth::user()->id;
						$access_data['sys_time'] = time();
						$access_data['sys_ip'] = ip2long($request->ip());
						
						$user_access_insert[] = $access_data;
						unset($access_data);
					}	
				}
				else
				{
					
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{		
						$ip_conflict = false;
						
						if (!empty($bound_ips))
						{
							foreach($bound_ips as $b_ip_k => $b_ip_v)
							{
								if ( ($article_id == $b_ip_v['article_id']) && ($b_ip_v['to_ip'] >= $ip_v['from_ip'] && $b_ip_v['from_ip'] <= $ip_v['to_ip']))
								{
									$ip_conflict = true;
									$conflict_ip['user'] = $request->user_name;
									$conflict_ip['journal_id'] = $journal_id;
									$conflict_ip['volume_id'] = $volume_id;
									$conflict_ip['issue_id'] = $issue_id;
									$conflict_ip['article_id'] = $article_id;
									$conflict_ip['user_ips'] = long2ip($ip_v['from_ip']) .' - '. long2ip($ip_v['to_ip']);
									$conflict_ip['conflict_user_id'] = $b_ip_v['conflict_user_id'];
									$conflict_ip['conflict_ips'] = long2ip($b_ip_v['from_ip']) .' - '. long2ip($b_ip_v['to_ip']);
									$conflict_ips[] = $conflict_ip;
								}
							}
						}
						
						if ($ip_conflict == false)
						{
							$access_data['user_access_id'] = $param['user_access_id'];
							$access_data['journal_id'] = $journal_id;
							$access_data['volume_id'] = $volume_id;
							$access_data['issue_id'] = $issue_id;
							$access_data['article_id'] = $article_id;
							$access_data['user_id'] = $param['user_id'];
							
							$access_data['from_ip'] = $ip_v['from_ip'];
							$access_data['to_ip'] = $ip_v['to_ip'];
							
							$access_data['type'] = $request->access_type_id;
							
							
							if ($request->perpetual == 1)
							{
								$access_data['perpetual'] = $request->perpetual; 
							}
							else
							{
								$access_data['from_date'] = $request->from_date;  
								$access_data['to_date'] = $request->to_date; 
							}
							
							$access_data['sys_user_id'] = Auth::user()->id;
							$access_data['sys_time'] = time();
							$access_data['sys_ip'] = ip2long($request->ip());
							
							$user_access_insert[] = $access_data;
							
							unset($access_data);
						}
					}
				}
			}
			
			if (!empty($conflict_ips))
			{
				$request->conflict_ips = $conflict_ips;
			}
			
			
			return $user_access_insert;
		}
	}
	
	public function add_user_access_chapter_user_base($request,$dup_content,$param)
	{
		$access_data = array();
		$user_access_insert = array();
		
		if(!empty($request->chapter))
		{
		
			foreach($request->chapter as $k => $v)
			{
				$vals = explode(',',$v);
			
				$ebook_id = $vals[0];
				$ebook_volume_id = $vals[1];
				$chapter_id = $vals[2];	
				
				$dup_vol = false;
				if (!empty($dup_content))
				{
					foreach($dup_content as $dup_k => $dup_v)
					{
						if ($chapter_id == $dup_v->chapter_id)
						{
							$dup_vol = true;break;
						}
					}
				}
					
				if ($dup_vol == false)
				{
					$access_data['user_access_id'] = $param['user_access_id'];
					$access_data['ebook_id'] = $ebook_id;
					$access_data['volume_id'] = $ebook_volume_id;
					$access_data['chapter_id'] = $chapter_id;
					$access_data['user_id'] = $param['user_id'];
					$access_data['type'] = $request->access_type_id;
					
					if ($request->perpetual == 1)
					{
						$access_data['perpetual'] = $request->perpetual; 
					}
					else
					{
						$access_data['from_date'] = $request->from_date;  
						$access_data['to_date'] = $request->to_date; 
					}
					$access_data['sys_user_id'] = Auth::user()->id;
					$access_data['sys_time'] = time();
					$access_data['sys_ip'] = ip2long($request->ip());
					
					$user_access_insert[] = $access_data;
					unset($access_data);
				}
			}
			return $user_access_insert;
		}
	}
	
	public function add_user_access_chapter_ip_base($request,$dup_content,$param)
	{
		
		$access_data = array();
		$user_access_insert = array();
		
		if(!empty($request->chapter))
		{
			foreach($request->chapter as $k => $v)
			{
				$vals = explode(',',$v);
				
				$ebook_id = $vals[0];	
				$ebook_volume_id = $vals[1];	
				$chapter_id = $vals[2];	
				
				$dup_chapter = '0';
				
				if (!empty($dup_content))
				{
					foreach($dup_content as $b_k => $b_v)
					{
						if ($b_v->chapter_id == $chapter_id)
						{
							$dup_chapter = $chapter_id;
							$bound_ip['conflict_user_id'] = $b_v->user_id;
							$bound_ip['volume_id'] = $b_v->volume_id;
							$bound_ip['chapter_id'] = $b_v->chapter_id;
							$bound_ip['from_ip'] = $b_v->from_ip;
							$bound_ip['to_ip'] = $b_v->to_ip;
							$bound_ips[] = $bound_ip;
						}
					}
				}
					
				if ($dup_chapter != $chapter_id)
				{
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{
						$access_data['user_access_id'] = $param['user_access_id'];
						$access_data['ebook_id'] = $ebook_id;
						$access_data['volume_id'] = $ebook_volume_id;
						$access_data['chapter_id'] = $chapter_id;
						$access_data['user_id'] = $param['user_id'];
						$access_data['from_ip'] = $ip_v['from_ip'];
						$access_data['to_ip'] = $ip_v['to_ip'];
						$access_data['type'] = $request->access_type_id;
						
						
						if ($request->perpetual == 1)
						{
							$access_data['perpetual'] = $request->perpetual; 
						}
						else
						{
							$access_data['from_date'] = $request->from_date;  
							$access_data['to_date'] = $request->to_date; 
						}
						
						$access_data['sys_user_id'] = Auth::user()->id;
						$access_data['sys_time'] = time();
						$access_data['sys_ip'] = ip2long($request->ip());
						
						$user_access_insert[] = $access_data;
						unset($access_data);
					}	
				}
				else
				{
					
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{		
						$ip_conflict = false;
						
						if (!empty($bound_ips))
						{
							foreach($bound_ips as $b_ip_k => $b_ip_v)
							{
								if ( ($chapter_id == $b_ip_v['chapter_id']) && ($b_ip_v['to_ip'] >= $ip_v['from_ip'] && $b_ip_v['from_ip'] <= $ip_v['to_ip']))
								{
									$ip_conflict = true;
									$conflict_ip['user'] = $request->user_name;
									$conflict_ip['ebook_id'] = $ebook_id;
									$conflict_ip['volume_id'] = $ebook_volume_id;
									$conflict_ip['chapter_id'] = $chapter_id;
									$conflict_ip['user_ips'] = long2ip($ip_v['from_ip']) .' - '. long2ip($ip_v['to_ip']);
									$conflict_ip['conflict_user_id'] = $b_ip_v['conflict_user_id'];
									$conflict_ip['conflict_ips'] = long2ip($b_ip_v['from_ip']) .' - '. long2ip($b_ip_v['to_ip']);
									$conflict_ips[] = $conflict_ip;
								}
							}
						}
						
						if ($ip_conflict == false)
						{
							$access_data['user_access_id'] = $param['user_access_id'];
							$access_data['ebook_id'] = $ebook_id;
							$access_data['volume_id'] = $ebook_volume_id;
							$access_data['chapter_id'] = $chapter_id;
							$access_data['user_id'] = $param['user_id'];
							$access_data['from_ip'] = $ip_v['from_ip'];
							$access_data['to_ip'] = $ip_v['to_ip'];
							$access_data['type'] = $request->access_type_id;
							
							if ($request->perpetual == 1)
							{
								$access_data['perpetual'] = $request->perpetual; 
							}
							else
							{
								$access_data['from_date'] = $request->from_date;  
								$access_data['to_date'] = $request->to_date; 
							}
							
							$access_data['sys_user_id'] = Auth::user()->id;
							$access_data['sys_time'] = time();
							$access_data['sys_ip'] = ip2long($request->ip());
							
							$user_access_insert[] = $access_data;
							
							unset($access_data);
						}
					}
				}
			}
			
			if (!empty($conflict_ips))
			{
				$request->conflict_ips = $conflict_ips;
			}
			
			
			return $user_access_insert;
		}
	}

	public function add_user_access_disease_user_base($request,$dup_content,$param)
	{	
		$access_data = array();
		$user_access_insert = array();
		
		if(!empty($request->disease))
		{
		
			foreach($request->disease as $k => $vals)
			{
		
				$disease_id = $vals;	
				
				$dup_disease = false;
				if (!empty($dup_content))
				{
					foreach($dup_content as $dup_k => $dup_v)
					{
						if ($disease_id == $dup_v->disease_id)
						{
							$dup_disease = true;
							break;
						}
					}
				}
					
				if ($dup_disease == false)
				{
					$access_data['user_access_id'] = $param['user_access_id'];
					$access_data['disease_id'] = $disease_id;
					$access_data['user_id'] = $param['user_id'];
					$access_data['type'] = $request->access_type_id;
					
					if ($request->perpetual == 1)
					{
						$access_data['perpetual'] = $request->perpetual; 
					}
					else
					{
						$access_data['from_date'] = $request->from_date;  
						$access_data['to_date'] = $request->to_date; 
					}
					$access_data['sys_user_id'] = Auth::user()->id;
					$access_data['sys_time'] = time();
					$access_data['sys_ip'] = ip2long($request->ip());
					
					$user_access_insert[] = $access_data;
					unset($access_data);
				}
			}
			return $user_access_insert;
		}
	}
	
	public function add_user_access_disease_ip_base($request,$dup_content,$param)
	{	
		$access_data = array();
		$user_access_insert = array();
		
		if(!empty($request->disease))
		{
			foreach($request->disease as $k => $vals)
			{
			
				$disease_id = $vals;	
				
				$dup_disease = '0';
				
				if (!empty($dup_content))
				{
					foreach($dup_content as $b_k => $b_v)
					{
						if ($b_v->disease_id == $disease_id)
						{
							$dup_disease = $disease_id;
							$bound_ip['conflict_user_id'] = $b_v->user_id;
							$bound_ip['disease_id'] = $b_v->disease_id;
							$bound_ip['from_ip'] = $b_v->from_ip;
							$bound_ip['to_ip'] = $b_v->to_ip;
							$bound_ips[] = $bound_ip;
						}
					}
				}
					
				if ($dup_disease != $disease_id)
				{
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{
						$access_data['user_access_id'] = $param['user_access_id'];
						$access_data['disease_id'] = $disease_id;
						
						$access_data['user_id'] = $param['user_id'];
						
						$access_data['from_ip'] = $ip_v['from_ip'];
						$access_data['to_ip'] = $ip_v['to_ip'];
						
						$access_data['type'] = $request->access_type_id;
						
						
						
						if ($request->perpetual == 1)
						{
							$access_data['perpetual'] = $request->perpetual; 
						}
						else
						{
							$access_data['from_date'] = $request->from_date;  
							$access_data['to_date'] = $request->to_date; 
						}
						
						$access_data['sys_user_id'] = Auth::user()->id;
						$access_data['sys_time'] = time();
						$access_data['sys_ip'] = ip2long($request->ip());
						
						$user_access_insert[] = $access_data;
						unset($access_data);
					}	
				}
				else
				{
					
					foreach($request->ip_range_list as $ip_k => $ip_v) // ips loop
					{		
						$ip_conflict = false;
						
						if (!empty($bound_ips))
						{
							foreach($bound_ips as $b_ip_k => $b_ip_v)
							{
								if ( ($disease_id == $b_ip_v['disease_id']) && ($b_ip_v['to_ip'] >= $ip_v['from_ip'] && $b_ip_v['from_ip'] <= $ip_v['to_ip']))
								{
									$ip_conflict = true;
									$conflict_ip['user'] = $request->user_name;
									$conflict_ip['disease_id'] = $disease_id;
									$conflict_ip['user_ips'] = long2ip($ip_v['from_ip']) .' - '. long2ip($ip_v['to_ip']);
									$conflict_ip['conflict_user_id'] = $b_ip_v['conflict_user_id'];
									$conflict_ip['conflict_ips'] = long2ip($b_ip_v['from_ip']) .' - '. long2ip($b_ip_v['to_ip']);
									$conflict_ips[] = $conflict_ip;
								}
							}
						}
						
						if ($ip_conflict == false)
						{
							$access_data['user_access_id'] = $param['user_access_id'];
							$access_data['user_id'] = $param['user_id'];
							$access_data['disease_id'] = $disease_id;
							
							$access_data['from_ip'] = $ip_v['from_ip'];
							$access_data['to_ip'] = $ip_v['to_ip'];
							
							$access_data['type'] = $request->access_type_id;
							
							
							if ($request->perpetual == 1)
							{
								$access_data['perpetual'] = $request->perpetual; 
							}
							else
							{
								$access_data['from_date'] = $request->from_date;  
								$access_data['to_date'] = $request->to_date; 
							}
							
							$access_data['sys_user_id'] = Auth::user()->id;
							$access_data['sys_time'] = time();
							$access_data['sys_ip'] = ip2long($request->ip());
							
							$user_access_insert[] = $access_data;
							
							unset($access_data);
						}
					}
				}
			}
			
			if (!empty($conflict_ips))
			{
				$request->conflict_ips = $conflict_ips;
			}
			
			
			return $user_access_insert;
		}
	}	

	public function InsertTokenInfo($request,$user_id,$user_access_id)
	{
		$limit = $request->download_limit;
		
		// Single Token Access
		if ($request->access_type_id == '444' && $limit > 0)
		{
			$password = Str::random(10);
			
			$token_access['user_name'] = 'User1-'. time();
			$token_access['password'] = $password;
			$token_access['user_id'] = $user_id;
			$token_access['user_access_id'] = $user_access_id;
			$token_access['request_id'] = decrypt($request->request_id);
			$token_access['system_time'] =  time();
			$token_access['system_user_ip'] = ip2long($request->ip());
			
			$param['access_on'] = $request->access_on;
			$token_id = UserAccess::InsertToken($param,$token_access);

		}
		
		//Multiple Token Access
		if ($request->access_type_id == '555' && $limit > 0)
		{
			for($i = 1; $i <= $limit; $i++)
			{
				
				$password = Str::random(10);
				
				$token_access['user_name'] = 'User'.$i.'-'.time();
				$token_access['password'] = $password;
				$token_access['user_id'] = $user_id;
				$token_access['user_access_id'] = $user_access_id;
				$token_access['request_id'] = decrypt($request->request_id);
				$token_access['system_time'] =  time();
				$token_access['system_user_ip'] = ip2long($request->ip());
				
				$param['access_on'] = $request->access_on;
				$token_id = UserAccess::InsertToken($param,$token_access);
				
			}
		}
		
		// Token Access With Key
		if ($request->access_type_id == '666' && $limit > 0)
		{
			$password = Str::random(10);
			
			$token_access['user_name'] = 'User1-'.time();
			$token_access['password'] = $password;
			$token_access['user_id'] = $user_id;
			$token_access['user_access_id'] = $user_access_id;
			$token_access['request_id'] = decrypt($request->request_id);
			$token_access['system_time'] =  time();
			$token_access['system_user_ip'] = ip2long($request->ip());
			
			$param['access_on'] = $request->access_on;
			$token_id = UserAccess::InsertToken($param,$token_access);

		}
	}
	
	public function UpdateTokenInfo($request,$param,$search)
	{
		$validator = Validator::make($request->all(), 
		[
		  "download_limit" => 'required|max:5000|numeric'
		]);
		
		if($validator->fails())
		{
			return View::make('admin.user_access.token_access_add',with(['param' => $param,'search' => $search]))->withErrors($validator->errors());
		} 
		else
		{
			$p['user_name'] = $request->get('user_name');
			$p['access_type'] = $request->get('access_type_id');
			$p['access_on'] = $request->get('access_on');
			$p['select'] = 'all';
			
			$user_access_info = UserAccess::GetTokenlimit($p);
			
			if (!empty($user_access_info))
			{
				$user_access_id = $user_access_info->user_access_id;
				
				$download_limit = $request->download_limit;	
				if ($download_limit > 0)
				{
					$old_token = $user_access_info->restricted_download_limit;
					$total_token = $download_limit + $old_token;
					
					try 
					{// try transaction start here for data integrity

						DB::beginTransaction();
						
						if ($user_access_info->access_type_id == 444 || $user_access_info->access_type_id == 666)
						{

							// check if Token does not exist
							$t_param['user_access_id'] = $user_access_id;
							$t_param['user_id'] = $user_access_info->user_id;
							$t_param['access_on'] = $user_access_info->access_type_on;
							$token_list = UserAccess::GetAccessTokenList($t_param);
							
							if (isset($token_list[0]) && !empty($token_list[0]))
							{
								// do not insert token 
							}
							else
							{
								// means token empty insert only one entry
								$password = Str::random(10);
								$token_access['user_name'] = 'User1-'.time();
								$token_access['password'] = $password;
								$token_access['user_id'] = $user_access_info->user_id;
								$token_access['user_access_id'] = $user_access_info->user_access_id;
								$token_access['request_id'] = decrypt($request->request_id);
								$token_access['system_time'] =  time();
								$token_access['system_user_ip'] = ip2long($request->ip());
								
								$param['access_on'] = $request->access_on;
								$token_id = UserAccess::InsertToken($param,$token_access);
							}
							
						}
						
						//Multiple Token Access
						if ($user_access_info->access_type_id == 555)
						{
							$start = $old_token+1;
							for($i = $start; $i <= $total_token; $i++)
							{
								$password = Str::random(10);
								
								$token_access['user_name'] = 'User'. $i .'-'.time();
								$token_access['password'] = $password;
								$token_access['user_id'] = $user_access_info->user_id;
								$token_access['user_access_id'] = $user_access_info->user_access_id;
								$token_access['request_id'] = decrypt($request->request_id);
								$token_access['system_time'] =  time();
								$token_access['system_user_ip'] = ip2long($request->ip());
								
								$param['access_on'] = $request->access_on;
								$token_id = UserAccess::InsertToken($param,$token_access);
							}
						}
						
						// Update Token Limit UserAccessInfo 
						$param['user_access_id'] = $user_access_info->user_access_id;
						$update['restricted_download_limit'] = $total_token;
						UserAccess::updateUserAccessInfo($user_access_id,$update);
						
						// Update Request In Proccessing
						$uc_request = UserAccessRequest::where('request_id',decrypt($request->request_id))->first();
						if ($uc_request->request_status == 'N')
						{
							$update_access_request = array(
								'request_id'             => decrypt($request->request_id),
								'request_status'         => 'P',
								'updated_ip'             => ip2long($request->ip()),
								'updated_on'             => time(),
								'updated_by'             => Auth::user()->id
								);

							UserAccessRequest::UpdateAccessRequest($update_access_request);
						}
						

						DB::commit();
						
						
					
					} 
					catch (Exception $e) 
					{
						DB::rollback();
						Session::flash('error', 'Somthing wrong with this page. Please try again!');
						return back();
					}
				}
			}
		}
		
		return redirect('admin/useraccess/view');
	}
	
	public function UpdateUserAccessDate($request,$param,$search)
	{
		$content=array();
		// try transaction start here for data integrity
		try 
		{
			DB::beginTransaction();
			
			if(!empty($request->request_id))
			{
				$request_id = decrypt($request->request_id);
			
				$user = User::where('name',$request->user_name)->first();
				
				// Get  User Acces of Selected User
				$ua_param['access_type_id'] = $request->access_type_id;
				$ua_param['access_type_on'] = $request->access_on;
				if($request->access_base_type == "ip_base_access")
				{
					$ua_param['access_base_type'] = 1;
				}
				elseif($request->access_base_type == "user_base_access")
				{
					$ua_param['access_base_type'] = 0;
				}
				$ua_param['user_id'] = $user->id;
				
				$user_access = UserAccess::GetUserAccess($ua_param);
				
				if(!empty($user) && !empty($user_access))
				{
					$param['sys_h_user_id'] = Auth::user()->id;
					$param['sys_h_time'] = time();
					$param['sys_h_ip'] = ip2long($request->ip());
					$param['user_id'] = $user->id;
					$param['request_id'] = $request_id;
					$param['user_access_id'] = $user_access->user_access_id;
					UserAccess::UpdateUserAccessDate($param);
					$param['success_msg'] = 'Date Updated Successfully';
				}
				else
				{
					$param['error_msg'] = 'Access Does Not Exist';

	              //  return Redirect::to('admin/article');
				}
				
				DB::commit();
			}
			
			return View::make('admin.user_access.user_access_date_add',with(['param' => $param,
				'search' => $search,
				'content' => $content]));
		
		} 
		catch (Exception $e)
		{

			DB::rollback();
			Session::flash('error', 'Somthing wrong with this page. Please try again!');
			return back();
		}
		
		
	}
	
	public function InsertUserAccessInfo($request)
	{	
		$user = User::where('name',$request->user_name)->first();
		$user_id = $user->id;
		
		if($user_id != false && $user_id > 0)
		{
			$access_type['user_id'] = $user_id;
			$access_type['access_org_id'] = $request->organization_id;
			$access_type['access_type_id'] = $request->access_type_id;	
			$access_type['access_type_on'] = $request->access_on;	
			$access_type['remarks'] = $request->user_remarks;
			$access_type['view_option']  = $request->view_option;
			
			if ($request->access_base_type == 'ip_base_access')
			{
				$access_type['access_base_type'] = 1;	
			}
			elseif ($request->access_base_type == 'user_base_access')
			{
				$access_type['access_base_type'] = 0;	
			}
			
			$access_type['system_ip'] = ip2long($request->ip());
			$access_type['system_user_id'] = Auth::user()->id;
			
			if ($request->perpetual == 1)
			{
				$access_type['perpetual'] = $request->perpetual;
			}
			else
			{
				$access_type['perpetual'] = 0;
				
				if (!empty($request->consortia_user_name))
				{
					$access_type['access_date_from'] = $request->from_date;
					$access_type['access_date_to'] = $request->to_date;
				}
				else
				{
					$access_type['access_date_from'] = $request->from_date = strtotime($request->from_date .' 00:00:00'); 
					$access_type['access_date_to']   = $request->to_date   = strtotime($request->to_date .' 23:59:59'); 
					
				}
			}
			
			if ( $request->access_type_id == '444' || $request->access_type_id == '555' || $request->access_type_id == '666') 
			{
				$access_type['restricted_download_limit'] = $request->download_limit;	
			}
			
			$access_type['system_time'] = time();
			$access_type['created_on'] = time();
			$access_type['created_by'] = Auth::user()->id;
			
			
			$user_access_id = UserAccessIpRange::insertAccessOnUser($access_type);
			
			User::where('id',$user_id)->update(array('access_organization_id'=>$request->organization_id));
			
			$uc_req['request_id'] = decrypt($request->request_id);
			$uc_req['user_access_id'] = $user_access_id;
			$uc_req['action'] = '"C"';
			$uc_req['sys_user_id'] = Auth::user()->id;
			$uc_req['sys_time'] = time();
			$uc_req['sys_ip'] = ip2long($request->ip());

			UserAccess::AddUserAccessWithRequest($uc_req);
			
			//if($request->access_on != "disease")
			if ($request->access_type_id == 444 || $request->access_type_id == 555 || $request->access_type_id == 666)			
			{
				// Check If Already Tokens Exist then Don't Insert Tokens
				$tkn_param['access_on'] = $request->access_on;
				$tkn_param['user_access_id'] = $user_access_id;
				$tkn_param['count'] = true;
				$tkn_exist = UserAccess::GetAccessTokenList($tkn_param);
				
				if ($tkn_exist == 0)
				{
					$this->InsertTokenInfo($request,$user_id,$user_access_id);
				}
			}

			return $user_access_id;
		}
	}

	public function SaveContentForm($request,$param,$search)
	{	
	
		if(!empty($request->consortia_user_name)) // User Access Consortia
		{
			// If Consortia Form is Submitting
			$validator = $this->validate_user_access_consortia($request);
			
		}
		else // User Access Normal
		{
			$validator = $this->validate_user_access($request);	
		}
		
		if ($validator->fails())
		{
			return View::make('admin.user_access.user_access_add',with(['param' => $param,
				'search' => $search,
				'validator' => $validator]))->withErrors($validator->errors());
		} 
		
		// try transaction start here for data integrity
		try 
		{
			DB::beginTransaction();

			$request_id = decrypt($request->request_id);
			
			if (!empty($request_id))
			{	
				if(!empty($request->consortia_user_name)) // User Access Consortia
				{
					// If Consortia Form is Submitting
					$this->CreateConsortiaUserAccessInfo($request,$param,$search);
				}
				$user_access_id = $this->InsertUserAccessInfo($request);
				
				if (!empty($user_access_id))
				{
					$user_access_info = UserAccess::where('user_access_id',$user_access_id)->first();
					
					$param['user_access_id'] = $user_access_info->user_access_id;
					$param['user_id'] = $user_access_info->user_id;
					$param['access_type_id'] = $user_access_info->access_type_id;
					$param['access_on'] = $request->access_on;
					
					if ($request->access_base_type == 'ip_base_access')
					{
						$request->ip_range_list = $this->validate_ip_range($request->ip_range_list,'submit');
						
						$dup_content = UserAccess::GetUserAccessIpBase($request->ip_range_list,$param);

							if ($request->access_on == 'journal_volume')
							{
								$user_access_insert = $this->add_user_access_volume_ip_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'ebook_volume')
							{
								$user_access_insert = $this->add_user_access_ebook_volume_ip_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'issue')
							{
								$user_access_insert = $this->add_user_access_issue_ip_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'article')
							{
								$user_access_insert = $this->add_user_access_article_ip_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'chapter')
							{
								$user_access_insert = $this->add_user_access_chapter_ip_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'disease')
							{
								$user_access_insert = $this->add_user_access_disease_ip_base($request,$dup_content,$param);
							}
					}
					elseif ($request->access_base_type == 'user_base_access')
					{
							$dup_content = UserAccess::GetUserAccessUserBase($param);
							
							if ($request->access_on == 'journal_volume')
							{
								$user_access_insert = $this->add_user_access_volume_user_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'ebook_volume')
							{
								$user_access_insert = $this->add_user_access_ebook_volume_user_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'issue')
							{
								$user_access_insert = $this->add_user_access_issue_user_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'article')
							{
								$user_access_insert = $this->add_user_access_article_user_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'chapter')
							{
								$user_access_insert = $this->add_user_access_chapter_user_base($request,$dup_content,$param);
							}
							elseif ($request->access_on == 'disease')
							{	
								$user_access_insert = $this->add_user_access_disease_user_base($request,$dup_content,$param);
							}
					}
					
					if (!empty($user_access_insert))
					{	
						UserAccess::InsertUserAccessOnContent($user_access_insert,$user_access_info,$param);
					}
					
					
					// Update Request In Proccessing 
					$update_access_request = array(
						'request_status' => 'P',
						'updated_ip' => ip2long($request->ip()),
						'updated_on' => time(),
						'updated_by' => Auth::user()->id
					);
					
					UserAccessRequest::where('request_id', $request_id)->update($update_access_request);
					
					$p['user_access_id'] = $user_access_info->user_access_id;
					$update['content_data'] = 1;
					$update['user_access_status'] = 1;
					UserAccess::updateUserAccessInfo($p,$update);
					
				}
			}
			
			DB::commit();
		
		} catch (Exception $e) {

			DB::rollback();
			Session::flash('error', 'Somthing wrong with this page. Please try again!');
			return back();
		}
		
		if(isset($request->conflict_ips))
		{
			$this->SendIpsConflictReport($request->conflict_ips,$user_access_id,$request->user_name,$param);
		}
		else
		{
			return redirect('admin/useraccess/add');
		}
			
	}
	
	
	public function GetContentForm($request,$param,$search)
	{	
		$content=array();

		$param['access_request'] = UserAccessRequest::where('request_id',decrypt($request->request_id))->first();
		
		if ($request->frm_search)
		{
			$validator = $this->validate_user_access($request);
			
			if ($validator->fails())
			{
				return View::make('admin.user_access.user_access_add',with(['param' => $param,
					'search' => $search,
					'validator' => $validator]))->withErrors($validator->errors());
			} 
		}
		
		if ($request->access_on == 'journal_volume')
		{
			//$param['journal_id'] = $request->journal_id;
			$param['content_type_id'] = 'null';
			$param['group'] = true;
			
			$join['journal_access'] = true;
			$join['journal'] = true;
			$join['year'] = true;
			
			$content = UserAccess::GetConditionalVolumes($param,$join);
			
		}
		elseif ($request->access_on == 'ebook')
		{
			//$param['ebook_id'] = $request->ebook_id;
			$param['content_type_id'] = 'null';
			$param['group'] = true;
			$join['ebook_access'] = true;
			$join['ebook'] = true;
			$join['year'] = true;
			
			$content = UserAccess::GetConditionalEbookVolumes($param,$join);
			
		}
		elseif ($request->access_on == 'ebook_volume')
		{
			//$param['ebook_id'] = $request->ebook_id;
			$param['content_type_id'] = 'null';
			$param['group'] = true;
			$join['ebook_access'] = true;
			$join['ebook'] = true;
			$join['year'] = true;
			
			$content = UserAccess::GetConditionalEbookVolumes($param,$join);
			
		}
		elseif ($request->access_on == 'issue')
		{
			$join['journal_access'] = true;
			$join['journal'] = true;
			$join['volume'] = true;
			$join['year'] = true;
	
			$p['journal_id'] = $request->get('journal_id');
			$p['volume_id'] = $request->get('volume_id');
			$p['content_type_id'] = 'null';
			
			$content = UserAccess::GetConditionalIssues($p, $join);
		}
		elseif ($request->access_on == 'article')
		{
			$join['journal_access'] = true;
			$join['journal'] = true;
			$join['volume'] = true;
			$join['issue'] = true;
			
			$p['journal_id'] = $request->get('journal_id');
			$p['volume_id'] = $request->get('volume_id');
			$p['issue_id'] = $request->get('issue_id');
			
			$p['content_type_id'] = 'null';
			
			$content = UserAccess::GetArticleWithOutContentAccess($p, $join);
			
		}
		elseif ($request->access_on == 'chapter')
		{
			$join['ebook_access'] = true;
			$join['ebook'] = true;
			$join['ebook_volume'] = true;
			$p['group'] = true;
			$p['ebook_id'] = $request->get('ebook_id');
			$p['ebook_volume_id'] = $request->get('ebook_volume_id');
			
			$p['content_type_id'] = 'null';
			
			$content = UserAccess::GetChapterWithOutContentAccess($p, $join);
		}
		elseif ($request->access_on == 'disease')
		{	
			$content = Disease::DiseaseParent();
			
		}
		return View::make('admin.user_access.user_access_add',with(['param' => $param,
			'search' => $search,
			'content' => $content]));
	}
	
	public function GetContentList($request,$param,$search)
	{	
		$content=array();
		$messages = [
			'ip_address.required_if' => 'please enter correct ip',
			'user_name.required' => 'please enter user name',
		];
		
		$rule['access_type_id'] = 'required';
		$rule['access_on'] 		= 'required';
		
		if ((empty($request->user_name) || !empty($request->ip_address)) && $request->frm_search == true)
		{
			$rule['ip_address'] = 'required|ipv4';
		}
		if (empty($request->ip_address) && $request->frm_search == true)
		{
			$rule['user_name'] = 'required';
		}
		
		$validator = Validator::make($request->all(),$rule,$messages);
		
		if ($validator->fails())
		{
			return View::make('admin.user_access.user_access_view',with(['param' => $param,
				'search' => $search,
				'validator' => $validator]))->withErrors($validator->errors());
		} 
		else 
		{
			if (!empty($request->access_on) && !empty($request->access_type_id))
			{
				if (!empty($request->ip_address) || !empty($request->user_name))
				{
					$param['journal_id'] = $request->journal_id;
					$param['volume_id'] = $request->volume_id;
					$param['ebook_volume_id'] = $request->volume_id;
					$param['ebook_id'] = $request->ebook_id;
					$param['issue_id'] = $request->issue_id;
					$param['article_id'] = $request->article_id;
					$param['chapter_id'] = $request->chapter_id;
					$param['disease_id'] = $request->disease_id;
					
					$param['access_type_id'] = $request->access_type_id;
					$param['ip_address'] = $request->ip_address;
					$param['access_on'] = $request->access_on;
					$param['user_name'] = $request->user_name;	
					
					$join['user_access_info'] = true; // Default True
					$join['user'] = true; // Default True
					
					if ($request->access_on == 'journal_volume')
					{
						$join['journal'] = $join['volume'] = $join['year'] = true;
					}
					if ($request->access_on == 'issue')
					{
						$join['journal'] = $join['volume'] = $join['year'] = $join['issue'] = true;
					}
					if ($request->access_on == 'article')
					{
						$join['journal'] = $join['volume'] = $join['year'] = $join['issue'] = $join['article'] = true;
					}
					if ($request->access_on == 'ebook_volume')
					{
						$join['ebook_volume'] = true;
					}
					if ($request->access_on == 'chapter')
					{
						$join['ebook_volume'] = $join['chapter'] = true;
					}
					
					if($request->access_on == 'disease')
					{	
						$join['disease'] = true;
						$param['access_type_id'] = 777; // Corporate Disease
					}
						$content =  UserAccess::GetUserAccessOnContent($param,$join);
				}
			}
		//	dd($content);
			return View::make('admin.user_access.user_access_view',with(['param' => $param,
				'search' => $search,
				'content' => $content]));
		}
	}

	//---------------------------Delete All IP Access Content----------------
	public function DeleteIPBaseContent($request,$param,$search)
	{	
		$content=array();

        $validator = Validator::make($request->all(),
            [
                'ip_range_list' => 'required',
                'user_name' => 'required',
            ]);
		
		if ($validator->fails())
		{
			return redirect()->back()->with('Error', 'Ip / User Name Should Not Be Empty.');
		} 
		else 
		{
			try 
			{// try transaction start here for data integrity

				DB::beginTransaction();

				if (!empty($request->access_on) && !empty($request->access_type_id) && !empty($request->ip_range_list) && !empty($request->user_name))
				{
					$user = User::where('name', '=', $request->user_name)->first();

					$request_id = decrypt($request->request_id);

					$request->ip_range_list = $this->validate_ip_range($request->ip_range_list,'submit');

					$param['access_type_id'] = $request->access_type_id;

					$param['user_access_id'] = $request->user_access_id;

					$param['access_on'] = $request->access_on;
					
					$param['user_id'] = $user->id;
			
					$content = UserAccess::GetUserAccessIpBaseDelete($request->ip_range_list,$param);
					//dd($content);
					if(count($content) > 0)
					{	
						$uc_id = 0;

						foreach($content as $v)
						{
							$content_ids[] = $v->uc_id;
							if($uc_id != $v->uc_id)
							{
								$access_user_ids[] = $v->user_access_id;
								$uc_id = $v->uc_id;
							}
						}

						//Add User Access Request
						$param['sys_user_id'] = Auth::user()->id;
						$param['sys_user_id'] = Auth::user()->id;
						$param['sys_time'] = time();
						$param['sys_ip'] = ip2long($request->ip());
						$param['access_type_id'] = $request->access_type_id;
						$param['request_id'] = $request_id;
						$param['access_on'] = $request->access_on;
						UserAccess::AddUserAccessRequest($param);

						$param['sys_h_user_id'] = Auth::user()->id;
						$param['sys_h_time'] = time();
						$param['sys_h_ip'] = ip2long($request->ip());

						UserAccess::DeleteUserAccessOnContent($content_ids,$param);

						//Check If All Content on User Access is removed
						//Then Set User Access Status 3
						
						// foreach($access_user_ids as $uc_id)
						// {
							$param['count'] = true;
							$param['user_access_id'] = $access_user_ids[0];
							$param['user_id'] = null;
							$uc_content = UserAccess::GetUserAccessOnContent($param);
							// dd($uc_content);

							if($uc_content-> count() == 0)
							{
								// Update UserAccessInfo Status 3
								UserAccess::where('user_access_id',$access_user_ids[0])->update(array('user_access_status'=>3));
							}
						// }

						// Update Request In Proccessing
						$uc_request = UserAccessRequest::where('request_id',$request_id)->first();
						
						if (!empty($uc_request) && $uc_request->request_status == 'N')
						{
							$update_access_request = array(
								'request_id'             => $request_id,
								'request_status'         => 'P',
								'updated_ip'             => ip2long($request->ip()),
								'updated_on'             => time(),
								'updated_by'             => Auth::user()->id
								);

							UserAccessRequest::UpdateAccessRequest($update_access_request);
						}

					}
					else
					{	
						$param['Error'] = 'Ip Content Not Found.';

						return View::make('admin.user_access.user_access_view',with(['param' => $param,
							'search' => $search, 'request' => $request]));
					}
				}
				
				DB::commit();

				$param['Success'] = '('.count($content).') Records Has Been Deleted Successfully.';
				$param['request_id'] = encrypt($request_id);
				return View::make('admin.user_access.user_access_view', with(['param' => $param,
					'search' => $search, 'request' => $request]));


			} 
			catch (Exception $e) 
			{
				DB::rollback();

				$param['Error'] = 'Something Went Wrong.';

				return View::make('admin.user_access.user_access_view',with(['param' => $param,
					'search' => $search, 'request' => $request]));
			}
		}
	}
	//-----------------------End Delete All Access Content-----------------------
	
	//---------------------------Delete Selected Access Content----------------
	public function DeleteContentList($request,$param,$search)
	{
		try 
		{
			DB::beginTransaction();
			
			
				$request_id = decrypt($request->request_id);
				
				$uc_id = 0;
				foreach($request->content as $k => $v)
				{
					$content_ids[] = $k;
					if($uc_id != $v)
					{
						$access_user_ids[] = $v;
						$uc_id = $v;
					}
				}

				//Add User Access Request
				$p['sys_user_id'] = Auth::user()->id;
				$p['sys_time'] = time();
				$p['sys_ip'] = ip2long($request->ip());
				$p['request_id'] = $request_id;
				$p['user_access_id'] = $request->user_access_id;
				$p['access_type_id'] = $request->access_type_id;
				$p['access_on'] = $request->access_on;
				UserAccess::AddUserAccessRequest($p);
			
				//Delete User Access on Content
				$p['sys_h_user_id'] = Auth::user()->id;
				$p['sys_h_time'] = time();
				$p['sys_h_ip'] = ip2long($request->ip());
				UserAccess::DeleteUserAccessOnContent($content_ids,$p);
				
				//Check If All Content on User Access is removed
				//Then Set User Access Status 3
				
				foreach($access_user_ids as $uc_id)
				{
					$p['count'] = true;
					$p['user_access_id'] = $uc_id;
					$uc_content = UserAccess::GetUserAccessOnContent($p);
					if(empty($uc_content))
					{
						// Update UserAccessInfo Status 3
						UserAccess::where('user_access_id',$uc_id)->update(array('user_access_status'=>3));
					}
				}
				
				// Update Request In Proccessing
				$uc_request = UserAccessRequest::where('request_id',$request_id)->first();
				
				if (!empty($uc_request) && $uc_request->request_status == 'N')
				{
					$update_access_request = array(
						'request_id'             => $request_id,
						'request_status'         => 'P',
						'updated_ip'             => ip2long($request->ip()),
						'updated_on'             => time(),
						'updated_by'             => Auth::user()->id
						);

					UserAccessRequest::UpdateAccessRequest($update_access_request);
				}
				
			DB::commit();
			
			return $this->GetContentList($request,$param,$search);
				
		} 
		catch (Exception $e) 
		{
			DB::rollback();
			return redirect()->back()->withErrors(['Error Ocurred']);
		}
		
	}
	//--------------------------- End Delete Selected Access Content----------------

	public function param($request)
	{	
		// Organixzation Form Parameter
		$param['country_id'] =  $request->get('country_id');
		$param['organization_name'] =  $request->get('organization_name');
		$param['organization_website'] =  $request->get('organization_website');
		//-----------------------------------------------------------------
		
		$param['organization_type'] =  $request->get('organization_type');
		
		if (!empty($param['organization_type']))
		{
			$param['consortia_user_name'] = $request->get('consortia_user_name');	
		}
		
		$param['request_id'] = $request->get('request_id');
		$param['access_type_id'] = $request->get('access_type_id');
		$param['download_limit']  = $request->get('download_limit');
		$param['token_limit']  = $request->get('token_limit');
		
		$param['sort']  = $request->get('sort');
		
		$param['limit']  = $request->get('limit');
		
		$param['org_name_search'] =  $request->get('org_name_search');
		$param['organization_id'] =  $request->get('organization_id');
		
		
		$param['user_name'] =  $request->get('user_name');
		$param['access_base_type']  = $request->get('access_base_type');
		$param['view_option']  = $request->get('view_option') ? $request->get('view_option') : 0;
		$param['access_on']  = $request->get('access_on');
		$param['page_limit']  = $request->get('page_limit') ? $request->get('page_limit') : 10;
		
		$param['user_remarks']  = $request->get('user_remarks');
		
		$param['perpetual']  = $request->get('perpetual');
		$param['from_date']  = $request->get('from_date');
		$param['to_date']  = $request->get('to_date');
		
		$param['ip_range_list']  = $request->get('ip_range_list');
		$param['ip_range']  = $request->get('ip_range');
		
		$param['ip_address']  = $request->get('ip_address');
		
		$param['ip_range_to']  = $request->get('ip_range_to');
		$param['ip_range_from']  = $request->get('ip_range_from');
		
		$param['journal_id']  = $request->get('journal_id');
		$param['ebook_id'] = $request->get('ebook_id');
		$param['ebook_volume_id']  = $request->get('ebook_volume_id');
		$param['volume_id']  = $request->get('volume_id');
		$param['issue_id']  = $request->get('issue_id');
		$param['chapter_id']  = $request->get('chapter_id');
		
		return $param;
	}
	
	
	public function SendIpsConflictReport($conflict_ips,$user_access_id,$user_name,$param)
	{	
	
		//--------------Get Conflict Users-------------------------
		foreach($conflict_ips as $ip_k_u => $ip_v_u)
		{
			$user_ids[] = $ip_v_u['conflict_user_id'];
		}
		
		//Remove Duplicate ids
		$user_ids = array_unique($user_ids);
		
		$conflict_users = User::whereIn('id',$user_ids)->get();
		//---------------------------------------------------------
		
		//--------------Get Article Name---------------------------
		if($param['access_on'] == 'article')
		{
			foreach($conflict_ips as $val)
			{
				$article_ids[] = $val['article_id'];
			}
			
			//Remove Duplicate ids
			$article_ids = array_unique($article_ids);
			
			$articles = Article::whereIn('article_id',$article_ids)->pluck( 'title','article_id');
		}
		//--------------------------------------------------------
		
		//--------------Get Issue Name----------------------------
		if($param['access_on'] == 'issue' || $param['access_on'] == 'article')
		{
			foreach($conflict_ips as $val)
			{
				$issue_ids[] = $val['issue_id'];
			}
			
			//Remove Duplicate ids
			$issue_ids = array_unique($issue_ids);
			
			$issues = Issue::whereIn('issue_id',$issue_ids)->pluck( 'title','issue_id');
		}
		//--------------------------------------------------------
		
		//--------------Get Volume Name---------------------------
		if($param['access_on'] == 'journal_volume' || $param['access_on'] == 'issue' || $param['access_on'] == 'article')
		{
			foreach($conflict_ips as $val)
			{
				$volume_ids[] = $val['volume_id'];
			}
			
			//Remove Duplicate ids
			$volume_ids = array_unique($volume_ids);
			
			$volumes = Volume::whereIn('volume_id',$volume_ids)->pluck( 'volume_name','volume_id');
		}
		//---------------------------------------------------------
		
		if($param['access_on'] == 'journal_volume' || $param['access_on'] == 'issue' || $param['access_on'] == 'article')
		{
			$journals = Journal::GetJournalTitle();	
		}
		
		//--------------Get Chapter Name----------------------
		if($param['access_on'] == 'chapter')
		{
			foreach($conflict_ips as $val)
			{
				$chapter_ids[] = $val['chapter_id'];
			}
			
			//Remove Duplicate ids
			$chapter_ids = array_unique($chapter_ids);
			
			$chapters = Chapter::whereIn('chapter_id',$chapter_ids)->pluck( 'title','chapter_id');
		}
		//--------------------------------------------------------
		
		//--------------Get Ebook Volume Name----------------------
		if($param['access_on'] == 'ebook_volume' || $param['access_on'] == 'chapter')
		{
			foreach($conflict_ips as $val)
			{
				$ebook_volume_ids[] = $val['volume_id'];
			}
			
			//Remove Duplicate ids
			$ebook_volume_ids = array_unique($ebook_volume_ids);
			
			$volumes = EbookVolume::whereIn('ebook_volume_id',$ebook_volume_ids)->pluck( 'volume_name','ebook_volume_id');
		}
		//--------------------------------------------------------
		
		if($param['access_on'] == 'ebook_volume' || $param['access_on'] == 'chapter')
		{
			$ebooks = Ebook::GetEbookTitle();
		}

		//--------------Get disease detail------------------------
		if(isset($conflict_ips[0]['disease_id']))
		{
			foreach($conflict_ips as $dis_k => $dis_v)
			{
				$disease_id[] = $dis_v['disease_id'];
			}
			
			//Remove Duplicate User ids
			$disease_id = array_unique($disease_id);
			
			$conflict_disease = Disease::whereIn('disease_id',$disease_id)->get();
		}
		//--------------------------------------------------------
		
		$head_line = array("New User","New User IPs","Conflict User","Conflict IPs");
		
		if($param['access_on'] == 'article') // Articles 
		{
			$head_line = array_merge(array("Sno","Journal title","Volume","Issue","Article"),$head_line);
		}
		elseif($param['access_on'] == 'chapter') // Chapters
		{
			$head_line = array_merge(array("Sno","Ebook Title","Ebook Volume","Chapter"),$head_line);
		}
		elseif($param['access_on'] == 'issue') // Issue
		{
			$head_line = array_merge(array("Sno","Journal title","Volume","Issue"),$head_line);
		}
		elseif($param['access_on'] == 'journal_volume') // Journal Volume
		{
			$head_line = array_merge(array("Sno","Journal title","Volume"),$head_line);
		}
		elseif($param['access_on'] == 'ebook_volume') // Ebook Volume
		{
			$head_line = array_merge(array("Sno","Ebook Title","Ebook Volume"),$head_line);
		}
		elseif($param['access_on'] == 'disease') // disease
		{
			$head_line = array_merge(array("Sno","Disease"),$head_line);
		}
	
		foreach($conflict_ips as $ip_k => $ip_v)
		{
			$line['sno'] = $ip_k+1;
			
			if(isset($ip_v['disease_id']))
			{	
				$line['disease_name'] = '';
				foreach($conflict_disease as $cnf_dis_k => $cnf_dis_v)
				{
					if($cnf_dis_v->disease_id == $ip_v['disease_id'])
					{
						$line['disease_name'] = $cnf_dis_v->disease_name;
						break;
					}
				}
			}
			elseif($param['access_on'] == 'article')
			{
				$line['title'] 	 = $journals[$ip_v['journal_id']];
				$line['volume']  = $volumes[$ip_v['volume_id']];
				$line['issue']	 = $issues[$ip_v['issue_id']];
				$line['article'] = $articles[$ip_v['article_id']];
			}
			elseif($param['access_on'] == 'chapter')
			{
				$line['title'] 	 = $ebooks[$ip_v['ebook_id']];
				$line['volume']  = $volumes[$ip_v['volume_id']];
				$line['chapter'] = $chapters[$ip_v['chapter_id']];
			}
			elseif($param['access_on'] == 'issue')
			{
				$line['title'] 	 = $journals[$ip_v['journal_id']];
				$line['volume']  = $volumes[$ip_v['volume_id']];
				$line['issue']	 = $issues[$ip_v['issue_id']];
			}
			elseif($param['access_on'] == 'journal_volume' && isset($volumes[$ip_v['volume_id']]))
			{
				$line['title'] 	 = $journals[$ip_v['journal_id']];
				$line['volume']  = $volumes[$ip_v['volume_id']];
			}
			elseif($param['access_on'] == 'ebook_volume' && isset($volumes[$ip_v['volume_id']]))
			{
				$line['title'] 	 = $ebooks[$ip_v['ebook_id']];
				$line['volume']  = $volumes[$ip_v['volume_id']];
			}
			
			$line['user'] = $ip_v['user'];
			$line['ip_from'] = $ip_v['user_ips'];
			
			$line['conflict_user'] = '';
			foreach($conflict_users as $cnf_k => $cnf_v)
			{
				if($cnf_v->id == $ip_v['conflict_user_id'])
				{
					$line['conflict_user'] = $cnf_v->name;
					break;
				}
			}
			
			$line['ip_to'] = $ip_v['conflict_ips'];
			$lines[] = $line;
			
		}
	
		
		$filename = $user_access_id.'_'.$user_name.'-'.time().'.csv';
		
		header('Content-Type: text/csv');
		header('Content-Disposition: attachment; filename="'.$filename.'"');
		$fp = fopen('php://output', 'wb');
		fputcsv($fp, $head_line);
		foreach($lines as $v)
		{
			fputcsv($fp, $v);	
		}
		
		fclose($fp);
		exit;
		
	}
	
	
	
	
	public function ExportTokenList($request)
    {
		
		$user = User::where('name',$request->user_name)->first();
		
		$p['access_on'] = $request->access_on;
		$p['user_id'] = $user->id;
		
		$token_list = UserAccess::GetAccessTokenList($p);
		
		if (isset($token_list) && !empty($token_list[0]))
		{
			if ($request->access_type_id == 444)
			{
				$this->export_single_download($request,$token_list);
			}
			elseif($request->access_type_id == 666)
			{
				$this->export_download_key($request,$token_list);
			}
			elseif($request->access_type_id == 555)
			{
				$this->export_multiple_download($request,$token_list);
			}
		}
    }
	
	public function export_single_download($request,$token_list)
	{
		$user_access = UserAccess::where('user_access_id',$token_list[0]->user_access_id)->first();
		$download_limit = $user_access->restricted_download_limit;
		$user_access_status = $user_access->user_access_status;

		$used_token = $token_list[0]->download_count;
		$available_token = $download_limit - $token_list[0]->download_count;
		
		header('Content-Type: text/csv');
		header('Content-Disposition: attachment; filename="usage_report.csv"');
		
		$head_line = array('user_name','password','Total Token','Available Tokens','Used Tokens','Content','Status','Access Assigned Date');
				
		$fp = fopen('php://output', 'wb');
		
		fputcsv($fp, $head_line);
		
		if($user_access_status == 1){$status = 'Active';}else{$status = 'Inactive';}; 

		$line[] = $token_list[0]->user_name;
		$line[] = $token_list[0]->password; 
		$line[] = $download_limit; 
		$line[] = $available_token; 
		$line[] = $used_token; 
		$line[] = $request->access_on;
		$line[] = $status;
		$line[] = strftime("%d-%m-%Y",$token_list[0]->system_time);
	
		fputcsv($fp,$line);
		unset($line);
		
		fclose($fp);
		exit;
		
	}
	
	public function export_download_key($request,$token_list)
	{
		$user_access = UserAccess::where('user_access_id',$token_list[0]->user_access_id)->first();
		$download_limit = $user_access->restricted_download_limit;
		$user_access_status = $user_access->user_access_status;
		
		$used_token = $token_list[0]->download_count;
		$available_token = $download_limit - $token_list[0]->download_count;
		
		header('Content-Type: text/csv');
		header('Content-Disposition: attachment; filename="usage_report.csv"');
		
		$head_line = array('user_name','password','Total Token','Available Tokens','Used Tokens','Content','Status','Access Assigned Date');
				
		$fp = fopen('php://output', 'wb');
		
		fputcsv($fp, $head_line);
		
		if($user_access_status == 1){$status = 'Active';}else{$status = 'Inactive';}; 

		$line[] = $token_list[0]->user_name;
		$line[] = $token_list[0]->password; 
		$line[] = $download_limit; 
		$line[] = $available_token; 
		$line[] = $used_token; 
		$line[] = $request->access_on;
		$line[] = $status;
		$line[] = strftime("%d-%m-%Y",$token_list[0]->system_time);
		
		fputcsv($fp,$line);
		unset($line);
		
		fclose($fp);
		exit;
		
	}
	
	public function export_multiple_download($request,$token_list)
	{
		header('Content-Type: text/csv');
		header('Content-Disposition: attachment; filename="usage_report.csv"');
		
		$head_line = array('user_name','password','Content','Availability','Access Assigned Date');
				
		$fp = fopen('php://output', 'wb');
		
		fputcsv($fp, $head_line);
		
		foreach($token_list as $token) 
		{
			
			if($token->download_count == 0){$status = 'available';}else{$status = 'unavailable';}; 

			$line[] = $token->user_name;
			$line[] = $token->password; 
			$line[] = $request->access_on;
			$line[] = $status;
			$line[] = strftime("%d-%m-%Y",$token->system_time);
			
			fputcsv($fp,$line);
			unset($line);
		}
		
		fclose($fp);
		exit;
		
	}
	
	public function CreateConsortiaUserAccessInfo($request,$param,$search)
	{
		if(!empty($request->consortia_user_name) && !empty($search['consortia']))
		{
			$request->access_org_id = $search['consortia']->access_org_id;
			$request->access_type_id = $search['consortia']->access_type_id;
			$request->access_on = $search['consortia']->access_type_on;
			$request->user_remarks = $search['consortia']->remarks;
			$request->view_option = $search['consortia']->view_option;
			
			if ($search['consortia']->access_base_type == '0')
			{
				$request->access_base_type = 'user_base_access';
			}
			if ($search['consortia']->access_base_type == '1')
			{
				$request->access_base_type = 'ip_base_access';
			}
			
			$request->perpetual = $search['consortia']->perpetual;
			$request->from_date = $search['consortia']->access_date_from;
			$request->to_date = $search['consortia']->access_date_to;
			$request->download_limit = $search['consortia']->restricted_download_limit;
			
			$param['user_access_id'] = $search['consortia']->user_access_id;
			$param['access_on'] = $search['consortia']->access_type_on;
			$param['access_type_id'] = $search['consortia']->access_type_id;
		
			if($request->access_on == 'journal_volume')
			{
				$param['group_by'] = 'volume_id';
				$uc_consortia =  UserAccess::GetUserAccessOnContent($param);
				
				$journal_epub = array();
				foreach($uc_consortia as $val)
				{
					$journal_arr[] = $val->journal_id .','. $val->volume_id;
					if($val->track == 1)
					{
						$journal_epub[$val->journal_id][$val->volume_id]['epub'] = $val->track;
					}
				}
				$request->journal_volume = $journal_arr;
				$request->journal_epub = $journal_epub;
			}
			
			if($request->access_on == 'ebook_volume')
			{
				$param['group_by'] = 'volume_id';
				$uc_consortia =  UserAccess::GetUserAccessOnContent($param);
				
				foreach($uc_consortia as $val)
				{
					$ebook_volume_arr[] = $val->ebook_id .','. $val->volume_id;
				}
				$request->ebook_volumes = $ebook_volume_arr;
			}
			if($request->access_on == 'issue')
			{
				$param['group_by'] = 'issue_id';
				$uc_consortia =  UserAccess::GetUserAccessOnContent($param);
				
				foreach($uc_consortia as $val)
				{
					$issue_arr[] = $val->journal_id .','. $val->volume_id .','. $val->issue_id;
				}
				$request->issue = $issue_arr;
			}
			if($request->access_on == 'article')
			{
				$param['group_by'] = 'article_id';
				$uc_consortia =  UserAccess::GetUserAccessOnContent($param);
				
				foreach($uc_consortia as $val)
				{
					$article_arr[] = $val->journal_id .','. $val->volume_id .','. $val->issue_id .','. $val->article_id;
				}
				$request->article = $article_arr;
			}
			if($request->access_on == 'chapter')
			{
				foreach($uc_consortia as $val)
				{
					$chapter_arr[] = $val->ebook_id .','. $val->ebook_volume_id .','. $val->chapter_id;
				}
				$request->chapter = $chapter_arr;
			}
				
			
		}
	}
	

	
	public function validate_ip_range($ip_range_list_text,$action)
	{
		
		$pri_addrs = array (
                      '10.0.0.0|10.255.255.255', // single class A network
                      '172.16.0.0|172.31.255.255', // 16 contiguous class B network
                      '192.168.0.0|192.168.255.255', // 256 contiguous class C network
                      '169.254.0.0|169.254.255.255', // Link-local address also refered to as Automatic Private IP Addressing
                      '127.0.0.0|127.255.255.255' // localhost
                     );
					
		foreach($pri_addrs as $pri_k => $pri_v)
		{
			$private_ip_range = explode('|',$pri_v);
			$ip_range_arr['from_ip'] = $private_ip_range[0];
			$ip_range_arr['to_ip'] = $private_ip_range[1];
			$ip_range_arr['from_ip_long'] = sprintf('%u',ip2long(ltrim(rtrim($private_ip_range[0]))));
			$ip_range_arr['to_ip_long'] = sprintf('%u',ip2long(ltrim(rtrim($private_ip_range[1]))));
			$private_ip_range_arr[] = $ip_range_arr;
		}	
		
		$ip_range_list = array();
		$invalid_ips = '';
		
		$ip_range_val = explode("\n", $ip_range_list_text);
		foreach($ip_range_val as $ip_range)
		{
			$ip_range = explode('-',$ip_range);
			
			$ip_range_arr['from_ip'] = sprintf('%u',ip2long(ltrim(rtrim($ip_range[0]))));
			$ip_range_arr['to_ip'] = sprintf('%u',ip2long(ltrim(rtrim($ip_range[1]))));
			
			$ip_range_list[] = $ip_range_arr;
			
			if($ip_range_arr['from_ip'] <= $ip_range_arr['to_ip'])
			{
				foreach($private_ip_range_arr as $k => $private_ip_val)
				{
					// IF IS PRIVATE
					if($private_ip_val['to_ip_long'] >= $ip_range_arr['from_ip'] && $private_ip_val['from_ip_long'] <= $ip_range_arr['to_ip'])
					{
						$invalid_ips .= rtrim($ip_range[0]) .' - '. rtrim($ip_range[1]).'<br>';
					}
/*					else
					{
						$ip_range_list[] = $ip_range_arr;
					}
*/				}
			}
			else
			{
				$invalid_ips .= rtrim($ip_range[0]) .' - '. rtrim($ip_range[1]).'<br>';
			}
			
		}
		
		
		if ($action == 'search')
		{
			return $invalid_ips;
		}
		if ($action == 'submit')
		{
			return $ip_range_list;
		}
	}
	
	public function validate_user_access($request)
	{
		
		$messages = [
				'perpetual.required_if' => 'aleast date or perpetual is required',
				'ip_range_list.required_if' => 'please enter ips range list',
				'user_name.exists' => 'User does not exist',
				'organization_id.required' => 'Organization Does Not Exist',
				'download_limit.required_if' => 'please insert download limit',
			];
			if(!$request->has('perpetual')){
				$request->query->set('perpetual','0');
			}
			$validator = Validator::make($request->all(),
			[
				'access_on'    => 'required',
				'access_type_id'     => 'required',
				'access_base_type' => 'required',
				'perpetual'       => 'required_if:from_date,""',
				'from_date'  => 'required_if:perpetual,0',
				'to_date'  => 'required_if:perpetual,0',
				'ip_range_list'  => 'required_if:access_base_type,ip_base_access',
				'user_name'  => 'exists:users,name',
				'journal_id' => 'required_if:access_on,issue|required_if:access_on,article',
				'volume_id' => 'required_if:access_on,issue|required_if:access_on,article',
				'issue_id' => 'required_if:access_on,article',
				'organization_id' => 'required:user_access_organizations,access_organization_id',
				
			],$messages);
		
			
			$validator->sometimes('download_limit', 'required|max:5000|numeric', function ($request) 
			{
				return ($request->access_type_id == '444' || $request->access_type_id == '555' || $request->access_type_id == '666');
			});
			
			$validator->after(function ($validator) use ($request)
			{
				$user_name = $request->get('user_name');
				$organization_id = $request->get('organization_id');
				
				// if User belong to another organization
				// Don't validate
				
				$user = User::where('name',$user_name)->first();
				
				if (!empty($user) && ($user->access_organization_id != null))
				{
					if ($user->access_organization_id != $organization_id)
					{
						$validator->errors()->add('user_name', 'User does not belong to this organization !');	
					}
				}
				
				$from_date = strtotime($request->get('from_date'));
				$to_date = strtotime($request->get('to_date'));
				
				if ($from_date > $to_date) 
				{
					$validator->errors()->add('from_date', 'Date Range is wrong !');
					$validator->errors()->add('to_date', 'Date Range is wrong !');
				}
				
				// Validate Ip Address
				$ip_range_list = $request->get('ip_range_list');
				if (isset($ip_range_list) &&  !empty($ip_range_list)) 
				{
					$invalid_ips = $this->validate_ip_range($ip_range_list,'search');
					
					if(!empty($invalid_ips))
					{
						$validator->errors()->add('ip_range_list', 'Below Ip Address are Invalid! <br>'.$invalid_ips);	
					}
				}
			
				$access_type_id = $request->get('access_type_id');
				$access_base_type = $request->get('access_base_type');
				
				// If User already have IP Base Don't Add User Base 
				// OR
				// If User already have User Base Don't Add IP Base
				
				if (!empty($user))
				{
					$user_access = UserAccess::where('user_id',$user->id)->where('user_access_status',1)->where('access_type_id',$access_type_id)->first();
					
					if (!empty($user_access))
					{
						if ($user_access->access_base_type == 1 && $access_base_type == 'user_base_access')
						{
							$validator->errors()->add('access_base_type', 'User Already has Ip Based Access !');	
						}
						if ($user_access->access_base_type == 0 && $access_base_type == 'ip_base_access')
						{
							$validator->errors()->add('access_base_type', 'User Already has User Based Access !');	
						}
					}
				}
				
			});
			
			return $validator;
	}
	
	public function validate_user_access_consortia($request)
	{
		$messages = [
			'ip_range_list.required_if' => 'please enter ips range list',
			'organization_id.required' => 'Organization Does Not Exist',
		];
		
		$validator = Validator::make($request->all(),
		[
			'ip_range_list'  => 'required_if:access_base_type,ip_base_access',
			'organization_id' => 'required:user_access_organizations,access_organization_id',
			
		],$messages);
		
		$validator->after(function ($validator) use ($request)
		{
			$new_user_name = $request->get('user_name');
			$consortia_user_name = $request->get('consortia_user_name');
			$organization_id = $request->get('organization_id');		
			
			$user = User::where('name',$new_user_name)->first();
			
			// if User does not exist
			// Don't validate
			if (empty($user))
			{
				$validator->errors()->add('user_name', 'User does not exist !');	
			}
			
			// if User belong to another organization
			// Don't validate
			if (!empty($user) && ($user->access_organization_id != null))
			{
				if ($user->access_organization_id != $organization_id)
				{
					$validator->errors()->add('user_name', 'User does not belong to this organization !');	
				}
			}
			
			// Consortia User and New User Should not be Unique
			if(rtrim($new_user_name) == rtrim($consortia_user_name))
			{
				$validator->errors()->add('user_name', 'User name must not be Consortia User !');
			}
			
			// Validate Ip Address
			$ip_range_list = $request->get('ip_range_list');
			if (isset($ip_range_list) &&  !empty($ip_range_list)) 
			{
				$invalid_ips = $this->validate_ip_range($ip_range_list,'search');
				
				if(!empty($invalid_ips))
				{
					$validator->errors()->add('ip_range_list', 'Below Ip Address are Invalid! <br>'.$invalid_ips);	
				}
			}
			
			// In Cosortia User should be IP Base 
			
			if (!empty($user))
			{
				$user_access = UserAccess::where('user_id',$user->id)->where('user_access_status',1)->first();

				if (!empty($user_access))
				{
					if ($user_access->access_base_type == 0)
					{
						$validator->errors()->add('user_name', 'User Already has User Based Access !');	
					}
				}
			}
			
		});
		
		return $validator;
	}
}

