<?php

namespace App\Http\Controllers\Auth;


use DB;
use Mail ;
use Session;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Http\Controllers\Action\Common;
class User 
{
	/*
	 *
	 */
	public $session = null;

	public $user_id = null ;

	public $email = null ;
	public $appType = 'SM' ;

	function __construct($userid=null,$appType='SM')
	{
		if (!empty($userid))
		{
			$user = $this->get($userid) ;
			if($user)
			{
				$this->email = $user[$_ENV['EMAIL']];
			}
		}
		if (!empty($appType))
		{
			//$this->appType = $appType;
		}
		
		$this->user_id = $userid;
        $this->market_list = array("ferrous","non-ferrous","coal","scrap-recycling");
		$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)
	{
		$sql = "SELECT";
		$sql .= " 	m.`id`,
					m.`id` as member_id, 
					m.`id` as memid, 
					m.`name`, 
					m.`username`, 
					CASE 
						WHEN m.send_email_to = 'R' then m.email
						ELSE m.addtnl_email
					END as email, 
					CASE 
						WHEN m.send_sms_to = 'R' then m.phoneno
						ELSE m.alternate_mob_no
					END as phoneno, 
					m.`address`, 
					m.`profile_pic`, 
					m.`company`, 
					m.`company_profile`, 
					m.`companytype` as company_type_id, 
					m.`job_title` as designation, 
					m.`pin_code`, 
					m.`mobile_notification`, 
					m.`verified`, 
					m.`protype`";

		$sql .= ", (SELECT ct.`name` FROM `tbl_companytype` ct WHERE ct.`id` = m.`companytype`) as company_type_name";
		//$sql .= ", (SELECT ee.`id` FROM `tbl_sm_events_events` ee WHERE ee.`status` = 1 LIMIT 1) as eventid";
		$sql .= ", m.`website`";
		$sql .= ", m.`department`";
		$sql .= ", m.`city`";
        $sql .= ", m.`state`";
        $sql .= ", m.`country`";
		$sql .= ", c.`name` as city_name";
		$sql .= ", s.`state_name` as state_name";
		$sql .= ", co.`country` as country_name";
		$sql .= ", co.`std_code`";

		$sql .= ", (SELECT COUNT(fs.`id`) FROM `final_status` fs WHERE fs.`registering_id` = m.`id` AND (fs.`closed` = 'Y' OR fs.`complementary` = 'Y') AND fs.`eventid` = (SELECT e.`id` FROM `tbl_sm_events_events` e WHERE e.`status` = 1 LIMIT 1)) as reg_to_applozic";

		$sql .= " FROM `tbl_members` m";
		$sql .= " LEFT JOIN `tbl_city` c ON(m.`city` = c.`id`)";
		$sql .= " LEFT JOIN `tbl_state` s ON(m.`state` = s.`id`)";
		$sql .= " LEFT JOIN `tbl_country` co ON(m.`country` = co.`id`)";

		$sql .= " WHERE m.`id` = '" . $user_id . "'";

		$result = DB::select($sql);

		if(isset($result[0]) && !empty($result[0])  ) {
			$location_ids = array();
			$location = array();

			if($result[0]['city']) {
				$location_ids[] = $result[0]['city'];
			} else {
				$location_ids[] = '0';
			}

			if($result[0]['state']) {
				$location_ids[] = $result[0]['state'];
			} else {
				$location_ids[] = '0';
			}

			if($result[0]['country']) {
				$location_ids[] = $result[0]['country'];
			} else {
				$location_ids[] = '0';
			}

			if($result[0]['city_name']) {
				$location[] = $result[0]['city_name'];
			}

			if($result[0]['state_name']) {
				$location[] = $result[0]['state_name'];
			}

			if($result[0]['country_name']) {
				$location[] = $result[0]['country_name'];
			}

			$result[0]['location_ids'] = implode(", ", $location_ids);
			$result[0]['location'] = implode(", ", $location);
			
			$companyType = array();
			$productType = array();

			$sql = "SELECT c.`id`, c.`name`";
			$sql .= ", CASE";
			$sql .= " WHEN c.`id` = '" . (!empty($result[0]['company_type_id']) ? $result[0]['company_type_id'] : 0) . "' THEN 1";
			$sql .= " ELSE 0 END as flag";
			$sql .= " FROM `tbl_companytype` c";

			$companyType = DB::select($sql);

			$result[0]['company_type'] = $companyType;

			if($result[0]['protype']) {
				$protypes = explode(",", rtrim(trim($result[0]['protype']), ","));
			}

			$sql = "SELECT p.`id`, p.`name`";
			$sql .= ", CASE";
			$sql .= " WHEN p.`id` = 0 " . (!empty($protypes) ? (" OR p.`id` = " . implode(" OR p.`id` = ", $protypes)) : '') . " THEN 1";
			$sql .= " ELSE 0 END as flag";
			$sql .= " FROM `tbl_producttype` p";

			$productType = DB::select($sql);
			
			
			$result[0]['isd_code'] = $result[0]['country_name'] . " " . $result[0]['std_code'];
			if( $result[0]['profile_pic'] != '' ){
				//$result[0]['profile_pic'] = "https://www.steelmint.com/images/clients/" . $result[0]['profile_pic'];
				$result[0]['profile_pic'] = BASEURL."images/clients/" . $result[0]['profile_pic'];
			}else{
				$result[0]['profile_pic'] = "";
				//$result[0]['profile_pic'] = "https://www.steelmint.com/images/clients/dummy_profile_pic.png";
				//$result[0]['profile_pic'] = BASEURL."images/clients/dummy_profile_pic.png";
			}
			$result[0]['product_type'] = $productType;

			//$result[0]['reg_to_applozic'] = !empty($result[0]['reg_to_applozic']) ? 'YES' : 'NO';
			$result[0]['reg_to_applozic'] = 'YES';

		}

		return $result[0];

	}	
	
	public function getProfile($user_id)
	{
		$sql = "SELECT";
		$sql .= " 	m.`id` as memid, 
					m.`name`, 
					m.`username` as `userName`, 
					CASE 
						WHEN m.send_email_to = 'R' then m.email
						ELSE m.addtnl_email
					END as email, 
					CASE 
						WHEN m.send_sms_to = 'R' then m.phoneno
						ELSE m.alternate_mob_no
					END as phoneno, 
					m.`email` as 'regEmail', 
					m.`addtnl_email` as 'alternateEmail',
					m.phoneno as 'regPhoneno',
					m.alternate_mob_no as 'alternatePhoneno',
					
					m.`dob` as 'DOB', 
					m.`job_title` as 'jobTitle', 					
					m.`company` as 'companyName', 
					m.`companytype` as 'companyType', 
					m.`address`, 
					m.`pin_code` as 'zipCode', 
					m.`profile_pic` as 'profilePic', 
					m.`isd_code` as 'isdCode'
					, m.`city`
					, m.`state`
					, m.`country`
					";
		
			$sql .= ", c.`name` as cityName";
			$sql .= ", s.`state_name` as stateName";
			$sql .= ", co.`country` as countryName";		

			$sql .= " FROM `tbl_members` m";
			$sql .= " LEFT JOIN `tbl_city` c ON(m.`city` = c.`id`)";
			$sql .= " LEFT JOIN `tbl_state` s ON(m.`state` = s.`id`)";
			$sql .= " LEFT JOIN `tbl_country` co ON(m.`country` = co.`id`)";

		$sql .= " WHERE m.`id` = '" . $user_id . "'";

		$result = DB::select($sql);

		if(isset($result[0]) && !empty($result[0])  ) {
			/* $location_ids = array();
			$location = array();

			if($result[0]['city']) {
				$location_ids[] = $result[0]['city'];
			} else {
				$location_ids[] = '0';
			}

			if($result[0]['state']) {
				$location_ids[] = $result[0]['state'];
			} else {
				$location_ids[] = '0';
			}

			if($result[0]['country']) {
				$location_ids[] = $result[0]['country'];
			} else {
				$location_ids[] = '0';
			}

			if($result[0]['cityName']) {
				$location[] = $result[0]['cityName'];
			}

			if($result[0]['stateName']) {
				$location[] = $result[0]['stateName'];
			}

			if($result[0]['countryName']) {
				$location[] = $result[0]['countryName'];
			}

			$result[0]['locationID'] = implode(", ", $location_ids);
			$result[0]['location'] = implode(", ", $location);
			
			$companyType = array();
			$productType = array(); */
			if($result[0]['cityName']) {
				$location[] = $result[0]['cityName'];
			}

			if($result[0]['stateName']) {
				$location[] = $result[0]['stateName'];
			}

			if($result[0]['countryName']) {
				$location[] = $result[0]['countryName'];
			}
			$result[0]['location'] = implode(", ", $location);
			
			$result[0]['stdCode'] = $result[0]['countryName'] . " " . $result[0]['stdCode'];
			if( $result[0]['profilePic'] != '' )
				$result[0]['profilePic'] = BASEURL."images/clients/" . $result[0]['profilePic'];
			else
				$result[0]['profilePic'] = "";
				//$result[0]['profilePic'] = BASEURL."images/clients/dummy_profile_pic.png";
			

			//$result[0]['reg_to_applozic'] = !empty($result[0]['reg_to_applozic']) ? 'YES' : 'NO';
			///$result[0]['reg_to_applozic'] = 'YES';

		}

		return $result[0];

	}
	/**
     * Get user's information from user's table
     * 
     * @param  $user_id: user's id
     * @return Database result 
     * comment: confirmed
     */
	public function get_old($user_id)
	{
//		echo "In get function";
		$result = DB::table($_ENV['USER_TABLE'])
							->select( 'username',
								'id' ,
								'address',
								'profile_pic',
//								'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'];
		
		$eventId = DB::table('tbl_sm_events_events')
			->select('id')
			->where( 'status' , '=' ,1 )
			->first()['id'];

			$reg_to_applozic = 
			 DB::select("
				SELECT  id
				FROM    final_status 
				WHERE   registering_id = $user_id
				AND		eventid = $eventId
				AND		(	complementary = 'Y'
							OR closed = 'Y'
				)
			"); 
			
			
		//$result['eventId'] = $eventId ;
		if(count($reg_to_applozic) > 0)
			$result['reg_to_applozic'] = 'YES' ;
		else
			$result['reg_to_applozic'] = 'NO';
		
		$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']) ;
		$result['member_id'] = strval($result['id']) ;

//		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, $resourceType='app', $appType='SM')
	{
		if($resourceType=='web'){
			return true;
			/* $result = DB::table('tb1_online_member')
				->select("mem_id" )
				->where("mem_id", '=', $user_id )
				->get();

			if (count($result) == 0 )
			{
				return false;
			} */
			
			DB::table('tb1_online_member')
				->where("mem_id", '=', $user_id )
				->delete();
				
			DB::table('tbl_members')
				->where($_ENV['USER_ID'], '=', $user_id )
				->update(['logstatus' => '', 'session' => '', 'logtime' => '']);
				
			DB::table('tb1_online_member_loggin_try')
							->where('mem_id', '=', $user_id )
							->where('is_loggedin', '=', 1 )
							->where('platform', '<>', 'Mobile APP' )
							->whereNotIn('device_name', array('android','IOS') )
							->update( [ 'is_loggedin' => 0, 'logoutBy' => 'self-SteelMint Web', 'logoutOn' => $GLOBALS['currDateTime']]);
							calculate_coc($user_id);			
			return true;
		}else{
			$result = DB::table($_ENV['REFRESH_TOKEN_TABLE'])
				->select($_ENV['USER_ID'] )
				->where($_ENV['USER_ID'], '=', $user_id )
				->where('appType', '=', $appType ) 
				->get();

			if (count($result) == 0 )
			{
				return false;
			}
			
			/* //set flag to logout by user
			$creden = DB::table('tb1_online_member_loggin_try')
					->select(array('id'))
					->where('mem_id', '=', $user_id )
					->whereIn('device_name', array('android','IOS') )
					->orderBy('id', 'desc')
					->first();
			
			///echo dd($creden[0]['id']); */		
			DB::table($_ENV['REFRESH_TOKEN_TABLE'])
				->where($_ENV['USER_ID'], '=', $user_id )
				->where('appType', '=', $appType ) 
				->delete();

			DB::table($_ENV['TOKEN_TABLE'])
				->where($_ENV['USER_ID'], '=', $user_id )
				->where('appType', '=', $appType ) 
				->delete();
			
			$creden = DB::table('tb1_online_member_loggin_try')
					->select(array('log_time'))
					->where('mem_id', '=', $user_id )
					->whereIn('device_name', array('android','IOS') )
					->orderBy('id', 'desc')
					->first();
					
			if(isset($creden[0]['log_time']) &&  strtotime($creden[0]['log_time'])> strtotime('2021-12-17 17:00:00')){
				$company = $appType=='SM'?'SteelMint':'CoalMint';
				DB::table('tb1_online_member_loggin_try')
							->where('mem_id', '=', $user_id )
							->where('is_loggedin', '=', 1 )
							->where('company', '=', $company )
							->whereIn('device_name', array('android','IOS') )
							->update( [ 'is_loggedin' => 2, 'logoutBy' => 'self-app', 'logoutOn' => $GLOBALS['currDateTime']]);
							calculate_coc($user_id);
			}else{
				DB::table('tb1_online_member_loggin_try')
							->where('mem_id', '=', $user_id )
							->where('is_loggedin', '=', 1 )
							->whereIn('device_name', array('android','IOS') )
							->update( [ 'is_loggedin' => 2, 'logoutBy' => 'self-app', 'logoutOn' => $GLOBALS['currDateTime']]);
			}				
			return true;
		}
		return false;
	}

	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;
	}
	
	public function checkEntryWithOthers($entry, $value, $user_id )
	{
		$result = DB::table($_ENV['USER_TABLE'])
							->select($entry)
							->where( $entry , '=', $value )
							->where( 'id' , '<>', $user_id )
							->get();
		if (count($result) == 0 )
			return false ;
		return true;
	}
	
	public function checkEntryWithSame($entry, $value, $user_id )
	{
		$result = DB::table($_ENV['USER_TABLE'])
							->select($entry)
							->where( $entry , '=', $value )
							->where( 'id' , '=', $user_id )
							->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,$appType)
	{
		$user = DB::table($_ENV['USER_TABLE'])
									->select($_ENV['USER_ID'], 'password')
									->where('username' , '=' , $email )
									->orWhere('email' , '=' , $email)
									->orWhere('addtnl_email' , '=' , $email)
									->first();
//echo "<br /> user:" . $user . ": $email" . "<br />";
		if($user) 
		{
			include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
		  	include env( 'MF_FILE_PATH' , '/home/steelmin/public_html/mf.php' ) ;
			forgotPassword($email, "MOBAPP", $appType) ;
			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_13NOV2024()
	{
		// if user id not set, means user not login
		if ( !empty($this->user_id) )
		{
			$temp_result = DB::table('tbl_updated_reg_logs_bm 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, (select packageName from tbl_packages where id=upd_rl.active_products) as sel_prods_1'))
				->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)
				{					if(intval($result['sel_prods'])>0){						$result['sel_prods'] = $result['sel_prods_1'];					}
					$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'], 'Platinum')!==false){
							$this->session[$result['f_product']]['userService'] = 'Platinum';
							$this->session[$result['f_product']]['userType'] = 1;
						//}else if($servTaken >= $totalItems){/// chk for complete access
						}elseif( strpos($this->session[$result['f_product']]['takenItems'], 'Silver')!==false){
							$this->session[$result['f_product']]['userService'] = 'Silver';
							$this->session[$result['f_product']]['userType'] = 1;
						//}else if($servTaken >= $totalItems){/// chk for complete access
						}
						elseif( strpos($this->session[$result['f_product']]['takenItems'], 'Gold')!==false){
							$this->session[$result['f_product']]['userService'] = 'Gold';
							$this->session[$result['f_product']]['userType'] = 1;
						//}else if($servTaken >= $totalItems){/// chk for complete access
						}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(strpos($this->session['MA_PO']['takenItems'], 'Price Only')!==false){/// chk for Mobile App
							$this->session['MA_PO']['userType'] = 3;
							$this->session['MA_PO']['userService'] = 'Upgrade';
						}else if(strpos($this->session[$result['f_product']]['takenItems'], 'Mobile App')!==false){/// chk for Mobile App
							//$this->session['W']['userType'] = 1;
							//$this->session['W']['userService'] = 'Standard';
							$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';
//						}
//					}
				}
				
				if(!isset($this->session['W']['userType'])){
					$this->session['W']['userType'] = 3;
					$this->session['W']['userService'] = 'Upgrade';
				}
				
				if(!isset($this->session['C']['userType'])){
					$this->session['C']['userType'] = 3;
					$this->session['C']['userService'] = 'Upgrade';
				}
				
				if(!isset($this->session['MA']['userType'])){
					$this->session['MA']['userType'] = 3;
					$this->session['MA']['userService'] = 'Upgrade';
				}
			}
			else
			{
				$this->session['W']['userType'] = 3;
				$this->session['W']['userService'] = 'Upgrade';
				$this->session['C']['userType'] = 3;
				$this->session['C']['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['C']['userType'] = 0;
			$this->session['C']['userService'] = 'Visitor';
			$this->session['MA']['userType'] = 0;
			$this->session['MA']['userService'] = 'Visitor';
		}
	}


	public function getTakenServicesByUser_13NOV2024($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 ;
		$f_product='W';
		
		if(!empty($this->user_id))
		{
			if($this->appType=='CM'){
				//echo $this->email.'ST:'.$this->appType;
				$f_product = 'C';
			}
			
			if($item=='MA_PO'){//price only
				$f_product = 'MA_PO';
			}
			
			if(empty($this->session[$f_product]['userService']) || empty($this->session['MA']['userService']))
				$this->getUserServices();
			///for steelmint MA
			if($this->appType!='CM' && $this->session['MA']['userService']=='ProductWise'){
				return -1;///paid active for MA
			}
			
			if($item=='MA_PO' && ($this->session['MA_PO']['userType']==3)){
				return -1;///paid active for MA_PO
			}
			
//			var_dump($this->session) ;
/* if($this->user_id==2){
echo '<pre>$this->appType:';
print_r($this->appType);
exit;
} */
 	
			$as_on_date = date('Y-m-d');
			$as_on_date = strtotime($as_on_date);
			$_fromdate = $fromdate = $_enddate = $enddate = '' ;
			if (!empty($this->session[$f_product]['startdate']))
			{
				$_fromdate = $this->session[$f_product]['startdate'];
				$fromdate = strtotime($this->session[$f_product]['startdate']);
			}
			if (!empty($this->session[$f_product]['enddate']))
			{
				$_enddate = $this->session[$f_product]['enddate'];
				$enddate = strtotime($this->session[$f_product]['enddate']);
			}


			$this->session['userType'] = $this->session[$f_product]['userType'];
			
			if ($as_on_date >= $fromdate && $as_on_date <= $enddate) //to free trial users show data for dates in his active tenure only
			{
				$rows_to_show=1;
			}else
				$rows_to_show=0;

			$fromdate = '' ;
			if (!empty($this->session[$f_product]['startdate']))
			{
				$fromdate = $this->session[$f_product]['startdate'];
			}
			
			if($this->appType!='CM' && $this->session['MA']['userType']==1)
				$userService = $this->session['MA']['userService'];
			else
				$userService = $this->session[$f_product]['userService'];

			
						/* var_dump($userService) ;
						var_dump($at_palce) ;
			dd(); */
/* //			var_dump($userService) ;

//			var_dump($this->session[$f_product]['product_items']) ;

			if($item=='coalmint' && $this->session['mid']){
				$userService = 'ProductWise';
			} */
/* if($this->user_id==56350){//prem 78616
	var_dump($userService);
	var_dump($this->session);
} */
			switch($at_palce){
				case "mobileapp":	//
					switch($userService){
						case "Gold":
						case "Platinum":
						case "Silver":
						case "Mobile App":
						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;
						elseif($userService=='Visitor')
							$maxCount = 1;
						else
							$maxCount = 0;
					}else{
						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 "Gold":
						case "Platinum":
						case "Silver":
						case "Mobile App":
						case "Enterprise":
						case "Professional":
						case "Standard":
						case "ProductWise":
						case "Free Trial":
							$maxCount = -1;
							break;
						case "Upgrade":
							$maxCount=0;
							break;
						default:
							$maxCount=1;//visitor
							break;
					}
					/* switch($userService)
					{
						case "VAS-P":
							$maxCount = -1; //premium user
							break;
						case "VAS-G":
							$maxCount = -1; //Basic or complete service user
							break;
						case "ProductWise":
							if( strpos(strtoupper($this->session[$f_product]['product_items']), strtoupper($item))!==false)
								$maxCount = -1; //Basic or complete service user
							else
								$maxCount = 0; //upgrade for product
							break;
						case "Free Trial":
							if($rows_to_show)
								$maxCount = 3;
							else
								$maxCount=0;//upgrade
							break;
						case "Upgrade":
							$maxCount=0;
							break;
						default:
							$maxCount=0;//visitor
							if(empty($this->session['tbl'.$type.$dPlace]) || $as_on_date=='' || ((!empty($this->session['tbl'.$type.$dPlace])) && $as_on_date==$this->session['tbl'.$type.$dPlace]))
								$maxCount = 1;
							else
								$maxCount = 0;
							break;
					} */
					break;
			}
		}
		else{
			$maxCount = 1;
		}
		
		/* if($this->user_id==56350){
echo "Max Count: $maxCount" ;
dd();
} */
//		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;
	}
	/*
		 - if both memid, packageID are present
			return true id memid has active packageID
		 - if only memid is present
			return 
				list array of 
					all active packages for memid
					package_order_id
				
		 - if both memid, packageID are absent
			return false
	*/
	public function accessiblePackagesToMemid($memid=0, $packageID=0 ,$status='Active')
	{
		$res=array();
		if($memid){
			if($packageID){//both memid, packageID are present
				$r = DB::table('tbl_reg_logs')
					->where('memid' , '=' , $memid)
					->where('status', '=', $status )
					->where('selected_products', '=', $packageID )
					->orderBy('id', 'desc')
					->get();
				if( count($r) > 0  )
					return true;
				else
					return false;
			}else{//
				/* $logs =  DB::table('tbl_packages')
					->leftJoin('tbl_reg_logs' , 'tbl_reg_logs.selected_products' , '=' , 'tbl_packages.id')
					->select(
						"tbl_packages.id" , 'tbl_packages.packageName', 'tbl_members.group_id', 'tbl_members.sub_group_id' , 'tbl_packages.package_order' )
					->where('tbl_reg_logs.memid' , '=' , $memid)
					->orderBy('tbl_packages.package_order', 'desc') 
					->get(); */
				$logs = DB::table('tbl_packages')
					->leftJoin('tbl_reg_logs', 'tbl_packages.id', '=', 'tbl_reg_logs.selected_products')
					//->select("tbl_packages.id as packages_id" , 'tbl_packages.packageName', 'tbl_packages.group_id', 'tbl_packages.sub_group_id' , 'tbl_packages.package_order', 'tbl_reg_logs.id as log_id' )
					->select("tbl_packages.*", 'tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate' )
					->where('tbl_reg_logs.memid' , '=' , $memid);
				
				if($this->appType=='CM'){
					$logs->where('tbl_reg_logs.f_product' , '=' , 'C');
				}else{
					$logs->where('tbl_reg_logs.f_product' , '<>' , 'C');
				}
				
				if($status=='Active')
					$logs->where('tbl_reg_logs.status' , '=' , 'Active');
				
				
				$logs =	$logs->get();
				///print_r($logs);
				foreach($logs as $r){
					$res['IDs'][$r['id']] = $r['package_order'];
					$res['packages'][] = array(
						"packageID"=>$r['id'],
						"packageOrder"=>$r['package_order'],
						"packageName"=>$r['packageName'],
						"periodName"=>$r['period_name'],
						"totalAmount_Wo_GST"=>$r['totalAmount_Wo_GST'],
						"currencyCode"=>$r['currency_code'],
						"currencySymbol"=>$r['currency_symbol'],
						"startDate"=>$r['startdate'],
						"endDate"=>$r['enddate']
					);
				}
				return $res;
			}
		}else
			return false;
		
	}
	
	/*
	    $section = 'prices/Report_r/Report_k/Report_s/insights/intel/360/infographs/tenders/'
	    $itemId = reportID in case special report
	    $itemDate = to check in between time
		output : sectionFromDate & sectionTodate => for where condition or use for Date Between
		
		0   =>  
		-1  =>  
		1   =>
	*/
	
	/////v2019 user services////
	public function isAccessible($resourceType="app", $section = 'prices', $itemID='', $itemDate='', $reportID=0,$market='',$commodity_arr=array())
	{
		/**
		 * If user services are not fetched from database, then we have to fetch and set in $this->session variable.
		 */
		$maxCount = 0 ;
		$f_product='W';
		$resourceType = strtolower($resourceType);
		if($resourceType=='')
		    $resourceType='app';
        /* if($market==''){
             $maxCount = 1;
             return $maxCount;
         }*/
        
		if(!empty($this->user_id))
		{
			DB::table('tbl_loggedin_users')
				->where("mem_id" , "=" , $this->user_id )
				->update(["log_time" => $GLOBALS['currDateTime'] ]) ;
				
			if($this->appType=='CM'){
			    $f_product = 'C';
			}elseif($resourceType=='app' ){///&& $this->appType!='CM'
			    $f_product = 'MA';
			}elseif($resourceType=='web'){
			    $f_product = $this->appType=='CM'?'C':'W';
			}elseif($section=='Report_s'){
			    $f_product = 'Report_s';
			}
			$this->getUserServicePackages();	
			Session::put('sectionsIncludes',$this->session['usrMarketWiseSection'][$f_product]);
			//Session::put('marketsIncludes',implode(',',array_unique($this->session['usrMarket'])));
			Session::put('marketsIncludes',implode(',',array_unique($this->session['usrMarketWithProduct'][$f_product])));	
			
			Session::put($this->session[$f_product]);	
		
			
			
			if( strtolower($section)=='report_k' && $this->appType=='CM'){
                $section = 'report_kc';
             } 
            if($market=='login'){
				
                 $sectionsIncludes = $this->session[$f_product][$market]['sectionsIncludes'];	
                if(isset($this->session[$section]) && !empty($this->session[$section])){
                    ///$itemID param => is used for included packages or reports
                    $maxCount = -1;//yes then check tenure of service
                }else{
                    return $maxCount = 0;////not include or taken the access of this section
                }	
            }else{
                 $sectionsIncludes = $this->session[$f_product][$market]['sectionsIncludes'];	
                if( strpos(strtolower($sectionsIncludes), strtolower($section))!==false || strpos($sectionsIncludes, $section)!==false || (strpos($sectionsIncludes, $itemID)!==false && isset($this->session[$section][$market]))){
                    ///$itemID param => is used for included packages or reports
                    $maxCount = -1;//yes then check tenure of service
                }else{
                return $maxCount = 0;////not include or taken the access of this section
                }
			}
			$as_on_date = $itemDate!=''?date('Y-m-d 00:01', strtotime($itemDate)):date('Y-m-d 00:01');
			$as_on_date = strtotime($as_on_date);
			$_fromdate = $fromdate = $_enddate = $enddate = '' ;
			
			$planType = $this->session[$f_product][$market]['userService'];
			if($this->appType=='CM'){
				$r = DB::table('tbl_packages_sectionwise_constraint')
    			->select('durationAgo', 'durationTill')
    			->where('section' , '=' , $section)
    			->where('planType', '=', $planType )
    			//->where('market', '=', $market )
    			->where('f_company', '=', $this->appType )
    			///->where('resourceType' , '=' , $resourceType)
    			->where('status' , '=' , 1)
    			->first();
			}else{
				$r = DB::table('tbl_packages_sectionwise_constraint')
    			->select('durationAgo', 'durationTill')
    			->where('section' , '=' , $section)
    			->where('planType', '=', $planType )
    			//->where('market', '=', $market )
    			->where('f_company', '=', $this->appType )
    			->where('resourceType' , '=' , $resourceType)
    			->where('status' , '=' , 1)
    			->first();
			}

			$durationAgo = isset($r['durationAgo'])?$r['durationAgo']:'';
			
			if (!empty($this->session[$f_product][$market]['startdate']))
			{
				$_fromdate = $this->session[$f_product][$market]['startdate'];
				$fromdate = strtotime($_fromdate . $durationAgo);
			}
			
			if (!empty($this->session[$f_product][$market]['enddate']))
			{
				$_enddate = $this->session[$f_product][$market]['enddate'];
				if($r['durationTill']!=''){
				    $enddate = strtotime($_enddate . $r['durationTill']);
				    //$enddate = strtotime($_fromdate . $r['durationTill']);
				}else{
				    $enddate = strtotime($_enddate);
				}
			}
			
			$enddate = strtotime(date('Y-m-d 23:59',$enddate));
			$this->session['userType'] = $this->session[$f_product][$market]['userType'];
			Session::put('userType', $this->session['userType']);
			if(!empty($commodity_arr) && strtolower($section)=='tenders'){
                  $get_res = $this->getMarketByCommodity($commodity_arr);
                  $maxCount=0;
                  
                  if($get_res['code']==1001){
                     $result=array_intersect(array_unique($this->session['usrMarketWithProduct'][$f_product]),$get_res['allowed_market']);                   
                        if (empty($result)) {
                            $maxCount=0;
                        }else{
                            $maxCount=-1;;
                        }
                    }
            }
			elseif (($as_on_date >= $fromdate && $as_on_date <= $enddate) || $r['durationTill']!='') //users show data for dates in his active tenure only
			{
				$maxCount = -1;//post
				$this->session[$f_product][$market]['sectionFromDate'] = date('Y-m-d',$fromdate);
				$this->session[$f_product][$market]['sectionTodate'] = date('Y-m-d',$enddate);
				Session::put($this->session[$f_product]);				
			}else
				$maxCount=0; //pre
		}
		else{
			$maxCount = 1;//not accessible
		}

		return $maxCount;
	}
	
	public function getUserServicePackages()
	{
		// if user id not set, means user not login
		if ( !empty($this->user_id) )
		{
			//$this->accessiblePackagesToMemid($memid=$this->user_id, $packageID=0 ,$status='Active');
	        $this->session['usrSession'] = 'set';
	        $this->session['usrMarket'] = array();	   
	        $this->session['usrMarketWithProduct'] = array();	
	        $this->session['usrMarketWiseSection'] = array();	   
			$temp_result = DB::table('tbl_updated_reg_logs_bm as upd_rl')
				->select(DB::raw('count(*) as cnt, startdate, enddate, upd_rl.services as f_product, upd_rl.paid_unpaid as f_tenure,f_market'), DB::raw('group_concat(DISTINCT active_products) as activePackageID'))
				->where('upd_rl.memid',   '=' , $this->user_id)
				->where('upd_rl.status',  '=' , 'Active')
				//->where('upd_rl.services','<>', 'M')
				->whereNotIn('upd_rl.services', array('M','EV'))
				//->groupBy(['f_product', 'f_tenure'])
				->groupBy(['f_product', 'f_market'])
				->get();

			if ($temp_result)
			{
				foreach ($temp_result as $result)
				{
                    $f_market_arr = explode(',',$result['f_market']);
                    foreach($f_market_arr as $mkt){
                        $this->session[$result['f_product']][$mkt]['startdate'] = $result['startdate'];
                        $this->session[$result['f_product']][$mkt]['enddate'] = $result['enddate'];
                    }
					if ($this->allowAccessToDownloaddataInEXCEL($this->email) == 1){
						//$this->session[$result['f_product']][$result['f_market']]['XLS']='XLS';
                        foreach($f_market_arr as $mkt){
                           $this->session[$result['f_product']][$mkt]['XLS']='XLS';
                        }
                    }
					
					/*if($result['f_product']=='C' && $result['f_market']=='coal') {
                        $this->session['W']['coal']['startdate'] = $result['startdate'];
                        $this->session['W']['coal']['enddate'] = $result['enddate'];
                        $this->session['W']['coal']['XLS']='XLS';
					}*/
					$activePackageID = $result['activePackageID'];
					$activePackageIDArr = explode(",",$activePackageID);
					//DB::enableQueryLog();
					$logs = DB::table('tbl_packages')
						->leftJoin('tbl_packages_includes', 'tbl_packages.group_id', '=', 'tbl_packages_includes.packageGroupID')
						//->select("tbl_packages.id as packages_id" , 'tbl_packages.packageName', 'tbl_packages.group_id', 'tbl_packages.sub_group_id' , 'tbl_packages.package_order', 'tbl_reg_logs.id as log_id' )
						->select("tbl_packages.ID", "tbl_packages.packageName", "tbl_packages.section", "tbl_packages.platform", "tbl_packages_includes.includeWithPackages", DB::raw('group_concat(DISTINCT sections_includes) as sections_includes'))
						//->where('tbl_packages.id' , '=' , $activePackageID)
						->whereIn('tbl_packages.id' , $activePackageIDArr)
						->groupBy(['section', 'platform'])
						->first();
					//dd(DB::getQueryLog());
					//print_r($logs);
                    foreach($f_market_arr as $mkt){
                        $this->session[$result['f_product']][$mkt]['userType'] = 1;
                        $this->session[$result['f_product']][$mkt]['userPackageID'] = $activePackageID;
                        $this->session[$result['f_product']][$mkt]['userService'] = $logs['section']=='report'?'Reports':$logs['packageName'];					
                        $this->session[$result['f_product']][$mkt]['sectionsIncludes'] = $logs['sections_includes'];
                        $this->session[$result['f_product']][$mkt]['includeWithPackages'] = $logs['includeWithPackages'];//	
                        $this->session[$result['f_product']][$mkt]['platform'] = $logs['platform'];//	
                        $this->session['usrMarket'][] = $mkt;
                        $this->session['usrMarketWithProduct'][$result['f_product']][] = $mkt;
                        $this->session['usrMarketWiseSection'][$result['f_product']][$mkt]=$logs['sections_includes'];
                    }
					
					/*if($result['f_product']=='C' && $result['f_market']=='coal') {
                        $this->session['W']['coal']['userType'] = 1;
                        $this->session['W']['coal']['userPackageID'] = $activePackageID;
                        $this->session['W']['coal']['userService'] = $logs['section']=='report'?'Reports':$logs['packageName'];					
                        $this->session['W']['coal']['sectionsIncludes'] = $logs['sections_includes'];
                        $this->session['W']['coal']['includeWithPackages'] = $logs['includeWithPackages'];//	
                        $this->session['W']['coal']['platform'] = $logs['platform'];//
					}*/
				    if($logs['includeWithPackages']!=''){
				         $includedPackageIDArr = explode(",",$logs['includeWithPackages']);
				        // DB::enableQueryLog();
    				     $includedLogs = DB::table('tbl_packages')
        					->leftJoin('tbl_packages_includes', 'tbl_packages.group_id', '=', 'tbl_packages_includes.packageGroupID')
        					//->select("tbl_packages.id as packages_id" , 'tbl_packages.packageName', 'tbl_packages.group_id', 'tbl_packages.sub_group_id' , 'tbl_packages.package_order', 'tbl_reg_logs.id as log_id' )
        					->select("tbl_packages.ID", "tbl_packages.packageName", "tbl_packages.section", "tbl_packages.platform", "tbl_packages_includes.includeWithPackages", DB::raw('group_concat(DISTINCT sections_includes) as sections_includes'))
        					->whereIn('tbl_packages.id' , $includedPackageIDArr)
        					//->whereIn('tbl_packages_includes.packageGroupID' , $includedPackageIDArr)
        					->groupBy(['section', 'platform'])
        					->get();
        					//dd(DB::getQueryLog());
        				    foreach($includedLogs as $log):
        				        if( strtolower($log['section'])=='report')
        				            $f_product_log = 'Report_s';
        				        elseif( strtolower($log['section']) =='event')
        				            $f_product_log = 'EV';
        				        elseif( strtolower($log['platform']) =='app')
        				            $f_product_log = 'MA';
        				        else
        				            $f_product_log = $log['section'];
        				    	foreach($f_market_arr as $mkt){
                                    $this->session[$f_product_log][$mkt]['startdate'] = $result['startdate'];
                                    $this->session[$f_product_log][$mkt]['enddate'] = $result['enddate'];        
                                    $this->session[$f_product_log][$mkt]['userType'] = 1;
                                    $this->session[$f_product_log][$mkt]['userPackageID'] = $log['ID'];
                                    $this->session[$f_product_log][$mkt]['userService'] = $log['section']=='report'?'Report_s':$log['packageName'];					
                                    $this->session[$f_product_log][$mkt]['sectionsIncludes'] = $log['sections_includes'];
                                //	$this->session[$f_product_log]['includeWithPackages'] = $log['includeWithPackages'];//	
                                    $this->session[$f_product_log][$mkt]['platform'] = $log['platform'];//	
                                    $this->session['usrMarket'][] = $mkt;
                                    $this->session['usrMarketWithProduct'][$f_product_log][] = $mkt;
                                    //$this->session['usrMarketWiseSection'][$f_product_log][$mkt]=$logs['sections_includes'];
                                     $this->session['usrMarketWiseSection'][$f_product_log][$mkt]=$log['sections_includes'];
            					}
            					
            					/*if($result['f_product']=='C' && $result['f_market']=='coal') {
                                    $this->session['W']['coal']['startdate'] = $result['startdate'];
                                    $this->session['W']['coal']['enddate'] = $result['enddate'];        
                                    $this->session['W']['coal']['userType'] = 1;
                                    $this->session['W']['coal']['userPackageID'] = $log['ID'];
                                    $this->session['W']['coal']['userService'] = $log['section']=='report'?'Report_s':$log['packageName'];					
                                    $this->session['W']['coal']['sectionsIncludes'] = $log['sections_includes'];                               
                                    $this->session['W']['coal']['platform'] = $log['platform'];//	
                                }*/
					
        				        
        				    endforeach;
				    }
				    
				}
				foreach($this->market_list as $mkt){
                    if(!isset($this->session['W'][$mkt]['userType'])){
                        $this->session['W'][$mkt]['userType'] = 3;
                        $this->session['W'][$mkt]['userService'] = 'Upgrade';
                    }
                    
                    if(!isset($this->session['C'][$mkt]['userType'])){
                        $this->session['C'][$mkt]['userType'] = 3;
                        $this->session['C'][$mkt]['userService'] = 'Upgrade';
                    }
                    
                    if(!isset($this->session['Report_s'][$mkt]['userType'])){
                        $this->session['Report_s'][$mkt]['userType'] = 3;
                        $this->session['Report_s'][$mkt]['userService'] = 'Upgrade';
                    }
                    
                    if(!isset($this->session['360'][$mkt]['userType'])){
                        $this->session['360'][$mkt]['userType'] = 3;
                        $this->session['360'][$mkt]['userService'] = 'Upgrade';
                    }
                    
                    if(!isset($this->session['MA'][$mkt]['userType'])){
                        if(isset($this->session['MA_PO'][$mkt]['userType'])){
                            $this->session['MA'][$mkt] = $this->session['MA_PO'];
                        }else{
                            $this->session['MA'][$mkt]['userType'] = 3;
                            $this->session['MA'][$mkt]['userService'] = 'Upgrade';
                        }
                    }
				}
			}
			else
			{
				foreach($this->market_list as $mkt){
                    $this->session['W'][$mkt]['userType'] = 3;
                    $this->session['W'][$mkt]['userService'] = 'Upgrade';
                    $this->session['C'][$mkt]['userType'] = 3;
                    $this->session['C'][$mkt]['userService'] = 'Upgrade';
                    $this->session['MA'][$mkt]['userType'] = 3;
                    $this->session['MA'][$mkt]['userService'] = 'Upgrade';
                    $this->session['Report_s'][$mkt]['userType'] = 3;
                    $this->session['Report_s'][$mkt]['userService'] = 'Upgrade';
                    $this->session['360'][$mkt]['userType'] = 3;
                    $this->session['360'][$mkt]['userService'] = 'Upgrade';
				}
			}


		}
		else
		{
			$this->session['W'][$mkt]['userType'] = 0;
			$this->session['W'][$mkt]['userService'] = 'Visitor';
			$this->session['C'][$mkt]['userType'] = 0;
			$this->session['C'][$mkt]['userService'] = 'Visitor';
			$this->session['MA'][$mkt]['userType'] = 0;
			$this->session['MA'][$mkt]['userService'] = 'Visitor';
			$this->session['Report_s'][$mkt]['userType'] = 0;
			$this->session['Report_s'][$mkt]['userService'] = 'Visitor';
			$this->session['360'][$mkt]['userType'] = 0;
			$this->session['360'][$mkt]['userService'] = 'Visitor';
		}
	   
	}
	
	function getMarketByCommodity($commodity_arr){
        $result=array();
		if(empty($commodity_arr) ){
			 return array("code" => 2001, "message" => "item id/section  blank","allowed_market"=>$result);
		}
		//$result = $commodityID;
		$result1 = $commodity_arr;
		/* $allowed_ids_market_wise= array (
            'ferrous' => 
            array (
            'commodity' => 
            array (
                0 => 408,
                1 => 410,
                2 => 413,
                3 => 403,
                4 => 412,
                5 => 980,
                6 => 407,
                7 => 402,
            ),
            'subcommodity' => 
            array (
                0 => 415,
                1 => 416,
                2 => 417,
                3 => 431,
            ),
            ),
            'non-ferrous' => 
            array (
            'subcommodity' => 
            array (
            ),
            'commodity' => 
            array (
                0 => 972,
            ),
            ),
            'coal' => 
            array (
            'subcommodity' => 
            array (
            ),
            'commodity' => 
            array (
                0 => 401,
                1 => 407,
            ),
            ),
            'scrap-recycling' => 
            array (
            'commodity' => 
            array (
                0 => 412,
                1 => 980
               
            ),
            'subcommodity' => 
            array (
                0 => 439,
                1 => 440,
                2 => 442,
                3 => 973,
                4 => 996,
                5 => 997,
            ),
            ),
        );
        
        
        $marketOfPage =array(); 
        foreach($allowed_ids_market_wise as $key=>$val) {
       
            if(!empty($val['commodity'])){
                if(in_array($result1['commodityID'], $val['commodity'])){
                    $marketOfPage[]=$key;
                   
                }
            }
            if(!empty($val['subcommodity'])){
                 if(in_array($result1['subCommodityID'], $val['subcommodity'])){
                    $marketOfPage[]=$key;
                } 
            }          
            
        }   */   
        $comm_arr = implode(",", $result1);
        $qry =  "select 
            GROUP_CONCAT(f_market) as market
            from tbl_region_commodity_master where id in ($comm_arr)  and itemtype='commodity' ";        
//         $res = mysql_query($qry);
//         $row = mysql_fetch_assoc($res);
        $resultData = DB::select($qry); 
        $marketOfPage= $resultData[0]['market'];
        
        $result = array_unique(explode(",",$marketOfPage));
      //  $result = array_unique($marketOfPage);
		return array("code" => 1001, "message" => "success", "allowed_market"=> $result);
	}
	
	//this is to check the access based on market or commodity 
	function isAccessibleMarketWise($market='',$commodity_arr=array()){
        if(empty($market) && !empty($commodity_arr)){
            $res = $this->getMarketByCommodity($commodity_arr);
            if($res['code']==1001){
                $f_market_arr = $res['allowed_market'];
            }
        }elseif(!empty($market))
            $f_market_arr = array_unique(explode(",",$market));
        //just match the market with user market 
        if(!empty($f_market_arr)){
            $userMarket = array_unique(explode(",",Session::get('marketsIncludes')));
            //$f_market_arr = array_unique(explode(",",$market));
            $result=array_intersect($userMarket,$f_market_arr);                   
            if (empty($result)) {
                $maxCount=0;//if market not accessible
            }else{
                $maxCount=-1; //if market accessible
            }
            return $maxCount;
        }
        
    }
    
    public function getMarketForAPPByItemID($resourceType,$itemID,$section='insights',$commodityID=array()){ 
        if(!empty($this->user_id) && (!empty($itemID) || !empty($commodityID))){
            $memid = $this->user_id;            
            $isAccessible = $this->isAccessible($resourceType,$section,'','','','');
            //getting market access for the user 
            $userMarket = array_unique(explode(",",Session::get('marketsIncludes')));
            $common = new Common();
            //getting markets of itemID
            if(strtolower($section)=='reports'){
                $get_market_data = $common-> getMarketByID(0,strtolower($section),$commodityID);              
            }
            else
                $get_market_data = $common-> getMarketByID($itemID,strtolower($section));
            $selected_market =$get_market_data['allowed_market'][0];    
            $allowed_market = $get_market_data['allowed_market'];
            //print_r($userMarket);
            //print_r($get_market_data);
            if(!empty($allowed_market)){
                $mkt_common = array_intersect($userMarket, $allowed_market);
                //checking if getting multiple common market 
                //print_r($mkt_common);
                if(count($mkt_common)==1){
                    $selected_market = reset($mkt_common);

                }elseif(count($mkt_common)>1){
                    //step-1 checking if user has any web services of any market of itemID
                   /* $webcheck_qry =  DB::table("tbl_updated_reg_logs_bm")
                                        ->select('f_market')
                                        ->where("services","=","W")
                                        ->where("memid","=",$memid)
                                        ->where("status","=","Active")
                                        ->where(function($webcheck_qry) use ($allowed_market) {
                                            foreach ($allowed_market as $market) {
                                                $webcheck_qry->orWhereRaw("FIND_IN_SET(?, f_market)", [$market]);
                                            }
                                        })
                                        ->orderBy('start_date', 'asc')
                                        ->first();*/
                    $webcheck_qry = 
                            DB::table('tbl_updated_reg_logs_bm as tbl_ulog')
                            ->select('tbl_ulog.f_market')
                            ->join('tbl_packages', function ($join) {
                                $join->on(DB::raw('FIND_IN_SET(tbl_packages.id, tbl_ulog.active_products)'), '>', DB::raw('0'));
                            })
                            ->where('tbl_ulog.services', 'W')
                            ->where('tbl_ulog.memid', $memid)
                            ->where('tbl_ulog.status', 'Active')
                            ->where(function ($query) use ($get_market_data) {
                                foreach ($get_market_data['allowed_market'] as $market) {
                                    $query->orWhereRaw('FIND_IN_SET(?, f_market)', [$market]);
                                }
                            })
                            ->orderBy('tbl_ulog.startdate', 'asc')
                            ->first();
                    if(!empty($webcheck_qry['f_market']))
                        $webcheck_mkt = array_filter(explode(',',$webcheck_qry['f_market']));
                    if(!empty($webcheck_mkt)){
                       $selected_market=$webcheck_mkt[0]; 
                      // echo "Getting From Web";
                      // print_r($webcheck_qry);
                    }
                    else{
                        //check for markets of  mobile-app active services
                         $appcheck_qry = DB::table('tbl_updated_reg_logs_bm as tbl_ulog')
                                        ->select('tbl_ulog.f_market')
                                        ->join('tbl_packages as packages', function ($join) {
                                            $join->on(DB::raw('FIND_IN_SET(packages.id, tbl_ulog.active_products)'), '>', DB::raw('0'));
                                        })
                                        ->where('tbl_ulog.services', 'MA')
                                        ->where('tbl_ulog.memid', $memid)
                                        ->where('tbl_ulog.status', 'Active')
                                        ->where(function ($query) use ($allowed_market) {
                                            foreach ($allowed_market as $market) {
                                                $query->orWhereRaw('FIND_IN_SET(?, tbl_ulog.f_market)', [$market]);
                                            }
                                        })
                                        ->orderBy('packages.fPriority', 'desc')  // Order by fPriority in descending order
                                        ->orderBy('tbl_ulog.startdate', 'asc')
                                        ->first();
                            if(!empty($appcheck_qry['f_market']))
                                $appcheck_mkt = array_filter(explode(',',$appcheck_qry['f_market']));
                            if(!empty($appcheck_mkt)){
                                $selected_market=$appcheck_mkt[0];                                
                                //echo "Getting From app";
                            }
                        
                    }
                    
                }              
                    
            }
            //echo "</pre>";
            //echo "return:".$selected_market;
            return $selected_market;
        }
	}
}
