<?php

namespace App\Http\Controllers\Auth;

use DB;
use Mail ;
use Symfony\Component\HttpFoundation\JsonResponse;

class User 
{
	/*
	 *
	 */
	public $session = null;

	public $user_id = null ;

	public $email = null ;

	function __construct($userid=null)
	{
		if (!empty($userid))
		{
			$user = $this->get($userid) ;
			if($user)
			{
				$this->email = $user[$_ENV['EMAIL']];
			}
		}
		$this->user_id = $userid;

		$this->session = array();
	}

	/**
	 * Create a new user
	 *
	 * @param  New user data
	 * @return $status
	 * $status Code:
	 * 0 = User created
	 * 1 = username exists
	 * 2	= email exists
	 * 3 = phone number exists
	 */

	public function create($username,
						   $password,
						   $email,
						   $company,
						   $name,
						   $phoneno,
						   $comments,
						   $country,
						   $state,
						   $ipAddress,
						   $source_from)
	{
		/**
		* Error Code: 
		* 1 = username exists 
		* 2	= email exists 
		* 3 = phone number exists
		* 4 = user varification email sending error
		*/

		$db_val = array();

		$db_val['tbl_members'] = array(
			"date"		=> date("Y-m-d H:i:s") ,
			"email"		=> $email,
			"company"	=> $company ,
			"name"		=> $name ,
			"phoneno"	=> $phoneno ,
			"alternate_mob_no" => $phoneno ,
			"comments"	=> "SteelMint Mobileapp" ,
			'billing_name'	=>	$name ,
			"username" 	=> $username,
			"password" 	=> $password ,
			"designation"	=> "",
			"country"	=> $country,
			"other_city" => "",
			"pin_code"	=> "",
			"ol_be"		=> 'MOB APP',
			"ipaddress" => $ipAddress ,
			"verified" 	=> 0,
			"addtnl_email" => $email ,
		);


		if(!empty($comments))
			$db_val['tbl_members']['comments'] = $comments ;

		if(!empty($state))
			$db_val['tbl_members']['state'] = $state ;

		if(!empty($ipAddress))
			$db_val['tbl_members']['ipaddress'] = $ipAddress ;


//		DB::table($_ENV['USER_TABLE'])->insert($db_val );
//		// Mail::send($email, $_ENV['STEELMINT_WELCOME_MAIL']. "<br> You can activate your account by following link<br><br>". )
//		$result = DB::table($_ENV['USER_TABLE'])
//				->select($_ENV['USER_ID'])
//				->where( 'email' , '=', $email )
//				->get() ;
//
//                $this->createRegLogs(date('H:i:s'), $result[0][$_ENV['USER_ID']], '0000-00-00', '0000-00-00',
//                        'Incomplete', 'W');
//                $this->createUpdatedRegLogs($result[0][$_ENV['USER_ID']], '0000-00-00', '0000-00-00',
//                        'Incomplete', 'W', 'not-paid');
//                $this->createComments($result[0][$_ENV['USER_ID']], date('Y-m-d'), date('H:i:s'),
//                        'New user registered from mobile app', 'API call', 'mobile app');

		include ($_ENV['COMMON_ROOT_PATH'].'/reg_process_steps.php') ;
		$res = processPersonalDetails('mobileapp' , 'online' , 'Free Trial' , $email , $db_val , $f_product='W',$price=0, $ipAddress, true ) ;

		return $res ;
	}

	/**
     * Get user's information from user's table
     * 
     * @param  $user_id: user's id
     * @return Database result 
     * comment: confirmed
     */
	public function get($user_id)
	{
//		echo "In get function";
		$result = DB::table($_ENV['USER_TABLE'])
							->select( 'username',
								'id' ,
								'address',
//								'subscriptionid as subscription' ,
								'city' ,
								'state',
								'country',
								'pin_code',
								'website',
								'companytype as company_type',
								'designation',
								'department',
								'billing_name as name',
								'company',
								'alternate_mob_no as phoneno',
								'addtnl_email as email',
								'address',
								'mobile_notification',
								'verified')
							->where( $_ENV['USER_ID'], '=', $user_id )
							->first() ;

		$result['country_name'] = DB::table('tbl_country')
			->select('country')
			->where( 'id' , '=' ,$result['country'] )
			->first()['country'];

		$result['state_name'] = DB::table('tbl_state_city')
			->select('state_name')
			->where( 'state_id' , '=' ,$result['state'] )
			->first()['state_name'];

		$result['city_name'] = DB::table('tbl_state_city')
			->select('city_name')
			->where( 'city_id' , '=' ,$result['city'] )
			->first()['city_name'];

		$result['phoneno'] = strval($result['phoneno']) ;
		$result['city'] = strval($result['city']) ;
		$result['state'] = strval($result['state']) ;
		$result['country'] = strval($result['country']) ;
		$result['company_type'] = strval($result['company_type']) ;
		$result['department'] = strval($result['department']) ;
		$result['designation'] = strval($result['designation']) ;
		$result['mobile_notification'] = strval($result['mobile_notification']) ;
		$result['verified'] = strval($result['verified']) ;

//		var_dump($result);

		if ( $result )
			return $result;
		return false;

	}

	/**
     * Delete user from database
     * 
     * @param  $user_id: user's id
     * @return Database result 
     */
	public function delete($user_id, $password)
	{

		if ( DB::table($_ENV['USER_TABLE'])
				->where( $_ENV['USER_ID'], '=', $user_id )
				->where('password', '=', $password)
				->delete() )
		{
			return true;
		}
		else
		{
			//log error, user not found or query error
			return false ;
		}
	}

	/**
     * Update user's info in database
     * 
     * @param  $user_id: user's id
     * @return Code: 
     * /**
		* Error Code: 
		* 0 = OK
		* 1 = username exists 
		* 2	= email exists 
		* 3 = phone number exists
		*
     */
	public function updateEntry($user_id, $field, $value, $old_pass= '')
	{
		/**
		* Error Code: 
		* 1 = OK
		* 2 = please enter old password for new password
		* 3	= email exists
		* 4 = phone number exists
		* 5 = field data empty
		 *6 = old password doesn't match with exiting password
		 *7 = invalid update request
		*/
		switch ($field)
		{
			case 'name':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('billing_name')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['billing_name'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'billing_name' => $value ]))
					return 1 ;

				break;

			case 'email':
				if ( $this->checkEntry('email' , $value))
					return 3 ;
				if ( $this->checkEntry('addtnl_email' , $value))
					return 3 ;

				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'addtnl_email' => $value ]))
				{
					return 1 ;
				}
				break;

			case 'phoneno':
				if ( $this->checkEntry('phoneno' , $value))
					return 4 ;
				if ( $this->checkEntry('alternate_mob_no' , $value))
					return 4 ;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'alternate_mob_no' => $value ]))
				{
					return 1 ;
				}
				break;

			case 'password':
				if (empty($old_pass))
				{
					return 2;
				}
				$result = DB::table($_ENV['USER_TABLE'])
					->select('password')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first();
				if($old_pass == $result['password'])
				{
					if ( DB::table($_ENV['USER_TABLE'])
						->where($_ENV['USER_ID'], '=', $user_id )
						->update( [ $field => $value ]))
					{
						return 1 ;
					}
				}
				else
					return 6;
				break;

			case 'company':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('company')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['company'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'company' => $value ]))
					return 1 ;
				break; 

			case 'company_type':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('companytype')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['companytype'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'companytype' => $value ]))
					return 1 ;
				break; 

			case 'product_of_interest':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('primary_company_products')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['primary_company_products'] ==  implode(', ',$value) )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'primary_company_products' => implode(', ',$value) ]))
					return 1 ;
				break; 

			case 'designation':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('designation')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['designation'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'designation' => $value ]))
					return 1 ;
				break; 

			case 'department':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('department')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['department'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'department' => $value ]))
					return 1 ;
				break; 

			case 'address':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('address')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['address'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'address' => $value ]))
					return 1 ;
				break; 

			case 'state':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('state')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['state'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'state' => $value ]))
					return 1 ;
				break; 

			case 'city':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('city')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['city'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'city' => $value ]))
					return 1 ;
				break;

			case 'country':
				if ( DB::table($_ENV['USER_TABLE'])
						->select('country')
						->where($_ENV['USER_ID'], '=', $user_id )
						->first()['country'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'country' => $value ]))
					return 1 ;
				break;

			case 'pin_code':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('pin_code')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['pin_code'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'pin_code' => $value ]))
					return 1 ;
				break; 

			case 'website':
				if ( DB::table($_ENV['USER_TABLE'])
					->select('website')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first()['website'] ==  $value )
					return 1;
				if ( DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'website' => $value ]))
					return 1 ;
				break; 

			default:
				return 5;
				break;
		}

		// field data empty
		return 5 ; 

	}

	/**
	 * Public function to delete all token from database
	 *
	 * @param  String: 	$user_id (user id )
	 * @return Boolean:	return true if successful
	 */
	public function userLogout($user_id)
	{
		$result = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
			->select($_ENV['USER_ID'] )
			->where($_ENV['USER_ID'], '=', $user_id )
			->get();

		if (count($result) == 0 )
		{
			return false;
		}

		DB::table($_ENV['REFRESH_TOKEN_TABLE'])
			->where($_ENV['USER_ID'], '=', $user_id )
			->delete();

		DB::table($_ENV['TOKEN_TABLE'])
			->where($_ENV['USER_ID'], '=', $user_id )
			->delete();
		return true;
	}

	public function userLogout_user_pass($username, $password)
	{
		$result = DB::table($_ENV['USER_TABLE'])
							->select($_ENV['USER_ID'] , $_ENV['VERIFIED_COLUMN'] )
							->where($_ENV['USERNAME'] ,$username)
							->where($_ENV['PASSWORD'] ,$password)
							->get();
		if (count($result) == 0 )
		{
			$result = DB::table($_ENV['USER_TABLE'])
				->select('email' , $_ENV['VERIFIED_COLUMN'], $_ENV['USER_ID'] )
				->where('email' ,$username)
				->where($_ENV['PASSWORD'] ,$password)
				->get();
			if (count($result) == 0 )
				return false;
		}

		if (count($result) == 1)
		{
			$user_id = $result[0][$_ENV['USER_ID']] ;
			$this->userLogout($user_id);
			return true;
		}
		return false;
	
	}

	/**
     * Private function to check entry in database
     * 
     * @param  String: 	$entry (field )
     *					$value (value )
     * @return Boolean:	return true if exists
     */
	private function checkEntry($entry, $value )
	{
		$result = DB::table($_ENV['USER_TABLE'])
							->select($entry)
							->where( $entry , '=', $value )
							->get();
		if (count($result) == 0 )
			return false ;
		return true;
	}

	private function generateActivationMail( $user_email)
	{
		$mail_activation_token = str_random($_ENV['MAIL_TOKEN_LENGTH']) ;
		$result = DB::table($_ENV['MAIL_ACTIVATION_TABLE'])->insert([ $_ENV['MAIL_ACTIVATION_USERID_COLUMN'] => $user_id, 
													$_ENV['MAIL_ACTIVATION_TOKEN_COLUMN'] => $mail_activation_token ]);

		if ( $result)
		{
			$activation_link = $_ENV['EMAIL_CONFIRMATION_LINK'].'/'.$mail_activation_token ; 
			//MAIL::send( $user_email, $message) ;

			$message_con = "Welcome to steelmint. To complete your registration please click the following link: ".$activation_link;

			$data = array( 'email' => $user_email , 'from' => $_ENV['MAIL_FROM'] );

			Mail::raw($message_con, function ($message) use ($data) {
			    $message->from($data['from']);
			    $message->subject('Steelmint activation');

			    $message->to($data['email']);
			});
			return 1; 
		}
		else 
			return 2; 
	}

	/**
     * Private function to check entry in database
     * 
     * @param  String: 	$code (mail activation code )
     *	
     * @return Boolean:	return 0 if all ok
		* Error Code: 
		* 0 = OK
		* 1 = token not exists in our database 
		* 2 = token exists but updating user table activation table problem
		* 3	= internal error, token exists more than once 
		* 4 = token not able to delete
		* 5 = verification table updation error
		*/
	public function activateMail( $code )
	{
		$result = DB::table( $_ENV['MAIL_ACTIVATION_TABLE'] )
							->select( $_ENV['MAIL_ACTIVATION_USERID_COLUMN'] )
							->where( $_ENV['MAIL_ACTIVATION_TOKEN_COLUMN'] , '=', $code )
							->get();

		// activation token found
		if (count($result) == 1 )
		{
		
			// Delete activation code from table 
			if ( DB::table($_ENV['MAIL_ACTIVATION_TABLE'])
				->where( $_ENV['MAIL_ACTIVATION_TOKEN_COLUMN'], '=', $code )
				->delete() )
			{

				//update database with verification true 
				if ( DB::table($_ENV['USER_TABLE'])
				->where($_ENV['USER_ID'], '=', $result[0][$_ENV['MAIL_ACTIVATION_USERID_COLUMN']] )
				->update( [ $_ENV['VERIFIED_COLUMN'] => 1] ) )
					return 0 ;
				else 
					return 5 ; 
			}
			else
				return 4 ; 

			
		}
		else if (count($result) == 0 )
		{
			return 1;
		}
		else 
		{
			return 2; 
		}

	}

	public function forgetPassword($email)
	{
		$user = DB::table($_ENV['USER_TABLE'])
									->select($_ENV['USER_ID'], 'password')
									->where('email' , '=' , $email )
									->first();

		if($user) 
		{
			include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
		  	include env( 'MF_FILE_PATH' , '/home/steelmin/public_html/mf.php' ) ;
			forgotPassword($email) ;
			include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php');
			return true;
		}
		return false;
		
	}
        
    public function createRegLogs( $fTime, $memid, $startdate, $enddate, $status,
            $fProduct) {
        
        DB::table($_ENV['REG_LOG_TABLE'])->insert([ 'f_time' => $fTime,
            'memid' => $memid,
            'startdate' => $startdate,
            'enddate' => $enddate,
            'status' => $status,
            'f_product' => $fProduct,
            'created_on' => date('Y-m-d H:i:s')]);
    }
        
    public function createUpdatedRegLogs( $memid, $startdate, $enddate, $status,
            $services, $paidUnpaid) {
        
        DB::table($_ENV['UPDATED_REG_LOG_TABLE'])->insert([ 'memid' => $memid,
            'startdate' => $startdate,
            'enddate' => $enddate,
            'status' => $status,
            'services' => $services,
            'paid_unpaid' => $paidUnpaid,
            'created_on' => date('Y-m-d H:i:s')]);
    }
        
    public function createComments( $memid, $fDate, $fTime, $comments,
            $createdBy, $commentsFor) {
        
        DB::table($_ENV['COMMENTS_TABLE'])->insert([ 'memid' => $memid,
            'f_date' => $fDate,
            'f_time' => $fTime,
            'comments' => $comments,
            'created_by' => $createdBy,
            'comments_for' => $commentsFor]);
    }


	/*
	 * User service module, User plan details
	 */
	/**
	 * Function for geting user'd subscribed service
	 * Set user's service in $this->session variable
	 * Case 1: If user is not login ($this->user_id is empty), then user is visitor
	 * Case 2: If user is login but in trail.
	 */
	public function getUserServices()
	{
		// if user id not set, means user not login
		if ( !empty($this->user_id) )
		{
			$temp_result = DB::table('tbl_updated_reg_logs as upd_rl')
				->select(DB::raw('count(*) as cnt, startdate, enddate, upd_rl.services as f_product, upd_rl.paid_unpaid as f_tenure, active_products as sel_prods'))
				->where('upd_rl.memid',   '=' , $this->user_id)
				->where('upd_rl.status',  '=' , 'Active')
				->where('upd_rl.services','<>', 'M')
				->groupBy(['f_product', 'f_tenure'])
				->get();

			if ($temp_result)
			{
				foreach ($temp_result as $result)
				{
					$this->session[$result['f_product']]['startdate'] = $result['startdate'];
					$this->session[$result['f_product']]['enddate'] = $result['enddate'];

					$rows = implode(',', array_keys(array_flip(explode(',', $result['sel_prods']))));

					$this->session[$result['f_product']]['takenItems'] = $rows;

					if ($this->allowAccessToDownloaddataInEXCEL($this->email) == 1)
						$this->session[$result['f_product']]['XLS']='XLS';
					$rows = explode(',', $rows);
					$rows = array_diff($rows, array("steelnews","Reports","VAS-G","VAS-P","XLS"));
					$servTaken = count($rows);

					$items_results = DB::table('tbl_product_items')
						->select('f_product', 'web_sms', 'f_items')
						->where('web_sms',   '=' , 'W')
						->where('f_price',  '>' , 0)
						->where('f_product','<>', 'Reports')
						->orderBy('f_product' , 'asc')
						->get();

					foreach ($items_results as $items)
					{
						if (in_array($items['f_product'] , $rows ))
							if(!empty( $this->session[$result['f_product']]['product_items']) )
								$this->session[$result['f_product']]['product_items'].=',';
						if( empty($this->session[$result['f_product']]['product_items']) )
							$this->session[$result['f_product']]['product_items'] = '';
						$this->session[$result['f_product']]['product_items'] .= $items['f_items'];

					}

					$date_diff=0;
					if( $result['f_tenure'] == 'Free_But_Standard' )
					{

						$this->session[$result['f_product']]['userType'] = 1;
						$this->session[$result['f_product']]['userService'] = 'Standard';

					}
					elseif( $result['f_tenure'] == 'not-paid' )
					{
						$this->session[$result['f_product']]['userType'] = 2;
						$this->session[$result['f_product']]['userService'] = 'Free Trial';
					}
					else{
						if( strpos($this->session[$result['f_product']]['takenItems'], 'Enterprise')!==false){
							$this->session[$result['f_product']]['userService'] = 'Enterprise';
							$this->session[$result['f_product']]['userType'] = 1;
							//}else if($servTaken >= $totalItems){/// chk for complete access
						}
						elseif( strpos($this->session[$result['f_product']]['takenItems'], 'Professional')!==false)
						{
							$this->session[$result['f_product']]['userService'] = 'Professional';
							$this->session[$result['f_product']]['userType'] = 1;
							//}else if($servTaken >= $totalItems){/// chk for complete access
						}
						else if(strpos($this->session[$result['f_product']]['takenItems'], 'Standard')!==false){/// chk for complete access
							$this->session[$result['f_product']]['userType'] = 1;
							$this->session[$result['f_product']]['userService'] = 'Standard';
						}
						else if($servTaken > 0){/// chk for complete access
							$this->session[$result['f_product']]['userType'] = 1;
							$this->session[$result['f_product']]['userService'] = 'ProductWise';
						}
						else{
							$this->session[$result['f_product']]['userType'] = 3;
							$this->session[$result['f_product']]['userService'] = 'Upgrade';
						}
					}
//					else{
//						if( strpos($this->session[$result['f_product']]['takenItems'], 'Enterprise')!==false){
//							$this->session[$result['f_product']]['userService'] = 'Enterprise';
//							$this->session[$result['f_product']]['userType'] = 1;
//							//}else if($servTaken >= $totalItems){/// chk for complete access
//						}else if(strpos($this->session[$result['f_product']]['takenItems'], 'Professional')!==false){/// chk for complete access
//							$this->session[$result['f_product']]['userType'] = 1;
//							$$this->session[$result['f_product']]['userService'] = 'Professional';
//						}else if(strpos($this->session[$result['f_product']]['takenItems'], 'Professional')!==false) {/// chk for complete access
//							$this->session[$result['f_product']]['userType'] = 1;
//							$$this->session[$result['f_product']]['userService'] = 'Professional';
//						}
//						else if($servTaken > 0){/// chk for complete access
//							$this->session[$result['f_product']]['userType'] = 1;
//							$this->session[$result['f_product']]['userService'] = 'ProductWise';
//						}else{
//							$this->session[$result['f_product']]['userType'] = 3;
//							$this->session[$result['f_product']]['userService'] = 'Upgrade';
//						}
//					}
				}
			}
			else
			{
				$this->session['W']['userType'] = 3;
				$this->session['W']['userService'] = 'Upgrade';
				$this->session['MA']['userType'] = 3;
				$this->session['MA']['userService'] = 'Upgrade';
			}


		}
		else
		{
			$this->session['W']['userType'] = 0;
			$this->session['W']['userService'] = 'Visitor';
			$this->session['MA']['userType'] = 0;
			$this->session['MA']['userService'] = 'Visitor';
		}
	}


	public function getTakenServicesByUser($item='', $at_palce='', $as_on_date='', $type='', $dPlace='')
	{
		/**
		 * If user services are not fetched from database, then we have to fetch and set in $this->session variable.
		 */
		$rows_to_show=0;
		$maxCount = 0 ;

		if(!empty($this->user_id))
		{
			if(empty($this->session['W']['userService']) || empty($this->session['MA']['userService']))
				$this->getUserServices();
			
			if($this->session['MA']['userService']!='Free Trial' && $this->session['MA']['userService']!='Visitor' && $this->session['MA']['userService']!='Upgrade'){
				return -1;///paid active for MA
			}
			
//			var_dump($this->session) ;
			$as_on_date = strtotime($as_on_date);
			$_fromdate = $fromdate = $_enddate = $enddate = '' ;
			if (!empty($this->session['W']['startdate']))
			{
				$_fromdate = $this->session['W']['startdate'];
				$fromdate = strtotime($this->session['W']['startdate']);
			}
			if (!empty($this->session['W']['enddate']))
			{
				$_enddate = $this->session['W']['enddate'];
				$enddate = strtotime($this->session['W']['enddate']);
			}

			$this->session['userType'] = $this->session['W']['userType'];			

			if ($as_on_date >= $fromdate && $as_on_date <= $enddate) //to free trial users show {
				$rows_to_show=1;
			}else
				$rows_to_show=0;

			$userService = $this->session['W']['userService'];

			switch($at_palce){
				case "mobileapp":	//
					switch($userService){
						case "Enterprise":
						case "Professional":
						case "Standard":
						case "ProductWise":
						case "Free Trial":
							$maxCount = -1;
							break;
						case "Upgrade":
							$maxCount=0;
							break;
						default:
							$maxCount=1;//visitor
							break;
					}
					/* if($item=='tenders')
					{
						if($userService=='Professional' || $userService=='Enterprise')
							$maxCount = -1;//all
						elseif($userService=='Visitor')
							$maxCount = 1;//login
						else
							$maxCount = 0;////upgrade
					}else{///news
						switch($userService){
							case "Enterprise":
							case "Professional":
							case "Standard":
							case "ProductWise":
							case "Free Trial":
								$maxCount = -1;
								break;
							case "Upgrade":
								$maxCount=0;
								break;
							default:
								$maxCount=1;//visitor
								break;
						}
					} */
					break;
				default:
					switch($userService)
					{
						case "Enterprise":
						case "Professional":
						case "Standard":
						case "ProductWise":
						case "Free Trial":
							$maxCount = -1;
							break;
						case "Upgrade":
							$maxCount=0;
							break;
						default:
							$maxCount=1;//visitor
							break;
					}
				break;
			}
		}
		else{
			$maxCount = 0;
		}
//		echo "Max Count: $maxCount" ;
		return $maxCount;
	}

	public function UpdateUserPlan($user_id, $plantype , $price )
	{

		$src_from='online';
		$source='mobileapp';
		// $require_srvc='VAS-P';
		$require_srvc = $plantype ;
		$memid=$user_id;
		$f_product='W';
		$price=$price;

		include ($_ENV['COMMON_ROOT_PATH'].'reg_process_steps.php') ;
		$r = processServiceDetailsBeforePymt($source, $src_from, $require_srvc, $memid, $f_product, $price);

		return $r ;
	}

	private function allowAccessToDownloaddataInEXCEL($email)
	{
		$email = strtolower($email);
		$curdate  = $GLOBALS['currDate'];
		$r = DB::table('tbl_allow_historical_data')
			->where('email' , '=' , $email)
			->where('startdate', '<=', $GLOBALS['currDate'] )
			->where('enddate' , '>=' , $GLOBALS['currDate'])
			->get();

		if( count($r) > 0  )
			return 1;
		return 0;
	}

	private function getAssesment($item='', $type='', $cond_type='',$f_cond=''){

		if(($item == 'IRON ORE' && strpos(strtoupper($f_cond), 'CHATTISGARH')!==false) || ($item == 'TMT' and $cond_type=='Primary'))
		{
			$assessement = 'MONTHLY';
		}
		elseif(($item== 'SCRAP' && $type=='DOM') || $item== 'SPONGE_IRON' || $item== 'SPONGE_PELLET'  || ($item == 'TMT' && $type=='DOM') || ($item== 'WIRE' && $type=='DOM') || ($item== 'BILLET' && $type=='DOM') || $item== 'INGOT' || ($item== 'IRON ORE' && $type=='E_I'))
		{
			$assessement = 'DAILY';
		}else
			$assessement = 'WEEKLY';

		return $assessement;
	}
}
