<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Response;
use App\Http\Controllers\Auth\authentication;
use App\Http\Controllers\Auth\User;
use DB;

class TokenController extends Controller
{
	/**
	 * Generate a request token.
	 * 
	 * @param  \Illuminate\Http\Request  $request
	 * @return \Illuminate\Http\Response
	 */
	private $debug = false;

	public function __construct(Request $request)
	{
		if ($request->has('debug') && $request->input('debug') == true) {
			$this->debug = true;
		}
	}

	public function refreshToken(Request $request)
	{
		if (($request->has('username') && $request->has('password')) || $request->has('token'))
		//if ( $request->has('username') && $request->has('password') )
		{
			/* if($request->has('token')) {
				
				$memidFrmToken = DB::table('tokens')
									->select('id')
									->where('token', '=', $request->input('token') )
									->get();		
									
				$creden = DB::table('tbl_members')
									->select(array('username','password'))
									
									->where('id', '=', $memidFrmToken[0]['id'] )
									->get();
				
				$username = $creden[0]['username'];					
				$password = $creden[0]['password'] ;					
			} else { 
			   $username = $request->input('username');
				$password = $request->input('password');
			}		*/


			$fcm_token = $request->input('fcm_token');
			$physical_id = $request->input('physical_id');

			$appType = 'SM';
			if ($request->has('appType') && strtoupper($request->input('appType')) == 'CM') {
				$appType = 'CM';
			}

			$auth = new authentication();
			if ($request->has('token')) {
				$refreshToken = $request->input('token');
			} else {
				$username = $request->input('username');
				$password = $request->input('password');
				$refreshToken = $auth->generateRefreshToken($username, $password);
			}

			$user_id = $auth->authRefreshToken($refreshToken);

			if ($this->debug) {
				echo "<br>userid:" . $username;
				echo "<br>userid:" . $password;
				echo "<br>refreshToken:" . $refreshToken;
				echo "<br>userid:" . $user_id;
			}

			if ($request->has('token') && empty($user_id)) {
				return new Response(array("code" => 401, "status" => false, "status#" => "", "message#" => 'Invalid Refresh Token'), 401);
			}

			$show_manage_pref_screen = 'no';
			/* if( $fcm_token != '' )
				$show_manage_pref_screen ='yes'; */

			if ($user_id) {
				if ($this->debug) {
					echo "yes, userid exists";
				}

				$rowExist = false;

				$rowExist = DB::table('gcm_device')
					// ->where('user_id', '=', $user_id )
					->where('device_id', '=', $fcm_token)
					->first();
				if ($this->debug) {
					echo "start<pre>";
					print_r($rowExist);
					echo "end<pre>";
				}

				if ($rowExist) {

					//$sql = "SHOW COLUMNS FROM `tbl_notification_preference`";
					$sql = "SHOW COLUMNS FROM `gcm_device`";
					$results = DB::select($sql);
					$columns = array();

					if ($results) {
						foreach ($results as $result) {
							$columns[] = $result['Field'];
						}
					}

					if ($this->debug) {
						echo "<pre>";
						print_r($columns);
						dd();
					}
					unset($columns[0]);
					unset($columns[1]);
					unset($columns[2]);
					unset($columns[3]);
					unset($columns[4]);
					unset($columns[5]);
					unset($columns[6]);
					unset($columns[7]);
					unset($columns[8]);
					unset($columns[9]);
					unset($columns[10]);
					unset($columns[11]);
					unset($columns[12]);
					unset($columns[13]);


					foreach ($columns as $column) {
						if (isset($rowExist[strtolower($column)]) && $rowExist[strtolower($column)] == 1) {
							$show_manage_pref_screen = 'no';
							break;
						}
					}

					DB::table('tb1_online_member_loggin_try')
						->where('mem_id', '=', $user_id)
						->where('is_loggedin', '=', 1)
						->where('platform', '=', 'Mobile APP')
						->whereIn('device_name', array('android', 'IOS'))
						->update(['is_loggedin' => 0, 'logoutBy' => 'when loggin from other device - app', 'logoutOn' => $GLOBALS['currDateTime']]);
					calculate_coc($user_id);
				}

				/*$show_manage_pref_screen = DB::table('tbl_notification_preference')
												->select('id')
												->where('member_id', '=', $user_id )
												->get();
				
				if(count($show_manage_pref_screen) >= 1){
					$show_manage_pref_screen ='yes';
				}*/



				$urlog = DB::table('tbl_reg_logs')
					->select('id')
					->where('status', '=', 'Active')
					->whereIn('f_product', array('W', 'MA'))
					->get();

				if (count($urlog) >= 1) {
					$_val = 10;
				} else
					$_val = 15;

				$result = DB::table($_ENV['USER_TABLE'])
					->select('*')
					->where($_ENV['USER_ID'], '=', $user_id)
					->first();

				DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id)
					->update(['activity_meter' => $result['activity_meter'] + $_val]);
			}

			if ($refreshToken == "NV") {
				return new Response(array("code" => 403, "status" => false, "status#" => "1003", "message#" => "Unauthorized action. Email not verified", "show_manage_pref_screen#" => $show_manage_pref_screen), 403);
				//             	abort(403, array( "status#" => "1003" , "message#" => "Unauthorized action. Email not verified"));

			} elseif ($refreshToken == 'MLR') {
				return new Response(array("code" => 409, "status" => false, "status#" => "1004", "message#" => "You are already loggedIn from some other device", "show_manage_pref_screen#" => $show_manage_pref_screen), 409);
				//             	abort(403, array( "status#" => "1003" , "message#" => "Unauthorized action. Email not verified"));

			} else if ($refreshToken) {
				/* $res = DB::table('tbl_reg_logs')
                                            ->select('id')
                                            ->where('memid', '=', $user_id )
                                            ->whereIn('f_product', array('W','MA') )
											->where('status', '=', 'Active' )
                                            ->where('inv_no', '<>', '' )
                                            ->where('amtPaid', '>', 0 )
                                            ->get();
				$userType = 'Upgrade';
				if (count($res) >= 1 ) {
					$userType = 'Renew';
				} */
				$userType = 'Upgrade';
				//if any active log then its paid
				if ($_val == 10)
					$userType = 'Renew';



				$user = new User($user_id);
				$user_data = $user->get($user_id);
				$dataArr = $user_data;
				//$dataArr= array ("refreshToken" => $refreshToken);
				$dataArr["refreshToken"] = $refreshToken;

				$auth = new authentication();
				$token = $auth->generateToken($refreshToken);
				if ($token) {
					$dataArr["token"] = $token;
				} else {
					$dataArr["token"] = "Unauthorized action. Token access denied";
				}

				$maxCount =	$user->getTakenServicesByUser();
				if ($maxCount == -1)
					$user_type = 'Paid';
				elseif ($maxCount == 0)
					$user_type = 'Upgrade';
				else
					$user_type = 'Login';

				//add as prem want seprate param for $user_type as $CM_user_type
				$CM_user_type = '';
				//if($appType=='CM'){
				$user1 = new User($user_id, 'CM');
				$maxCount_CM =	$user1->getTakenServicesByUser();
				if ($maxCount_CM == -1)
					$CM_user_type = 'Paid';
				elseif ($maxCount_CM == 0)
					$CM_user_type = 'Upgrade';
				else
					$CM_user_type = 'Login';
				//}

				DB::table("gcm_device")
					->where("device_id", '=', $fcm_token)
					->update(['user_id' => $user_id]);

				/*
			*		START: added by tarun
			*/
				/*  $rowExist = false;              
               
                 $rowExist = DB::table('gcm_device')
                            ->where('user_id', '=', $user_id )
                            ->first();            
                if($rowExist) {

                  //$sql = "SHOW COLUMNS FROM `tbl_notification_preference`";
                    $sql = "SHOW COLUMNS FROM `gcm_device`";
                    $results = DB::select($sql);
                    $columns = array();

                    if($results) {
                        foreach($results as $result) {
                            $columns[] = $result['Field'];
                        }
                    }

                    if($this->debug) {
					print_r ($columns);
					} 
                   

                    foreach($columns as $column) {
                        if(isset($rowExist[strtolower($column)]) && $rowExist[strtolower($column)] == 1) {
                            $show_manage_pref_screen = 'no';
                            break;
                        }
                    }
                } */

				/*
			*		END: added by tarun
			*/
				///maintain history of user loggin try.
				//added by mohan reddy
				//$userSysDtls = $_REQUEST['sender'] . '|' . $_REQUEST['tokinx'] . '|' . date('Y-m-d H:i');
				////if($physical_id!='' || $user_id==56350){


				/* if($physical_id!=''){
					$creden1 = DB::table('gcm_device')
                            ->select(array('device'))
                            ->where('device_id', '=', $device_id )
                            ->get(); 
				}else{
					$creden1 = DB::table('gcm_device')
                            ->select(array('device'))
                            ->where('physical_id', '=', $physical_id )
                            ->get(); 
				}
				$device_type = (isset($creden1[0]['device']))?$creden1[0]['device']:0; */

				$userSysDtls = $fcm_token . '|' . $refreshToken;
				$loggin_try['mem_id'] = $user_id;
				$loggin_try['log_time'] = $GLOBALS['currDateTime'];
				$loggin_try['log_date'] = date("Y-m-d");
				$loggin_try['ip_address'] = $_SERVER['REMOTE_ADDR'];

				$loggin_try['device'] = $userSysDtls;
				//$loggin_try['device_name'] = $device_type;

				if ($physical_id != '') {
					$loggin_try['company'] = ($appType == 'CM') ? 'CoalMint' : 'SteelMint';
					$loggin_try['device_id'] = $physical_id;
					$loggin_try['device_name'] = 'android';
				} else {
					$loggin_try['device_name'] = 'IOS';
					//$loggin_try['device_id'] = $fcm_token;
					if ($request->has('appType') && strtoupper($request->input('appType')) == 'CM') {
						$loggin_try['company'] = 'CoalMint';
					} else
						$loggin_try['company'] = 'SteelMint';
				}

				include_once('/home/steelmin/public_html/hf.php');
				$loggin_try['ip_country'] = ipTocntry($_SERVER['REMOTE_ADDR']);


				$creden = DB::table('tb1_online_member_loggin_try')
					->select(array('id'))
					->where('mem_id', '=', $user_id)
					->whereIn('device_name', array('android', 'IOS'))
					->where('company', '=', $loggin_try['company'])
					->get();

				$online_member_loggin_iid = (isset($creden[0]['id'])) ? $creden[0]['id'] : 0;
				$loggin_try['parent_loggedin_id'] = $online_member_loggin_iid;

				$loggin_try['platform'] = "Mobile APP";
				$loggin_try['url'] = "public/user/refresh_token : refreshToken - method";

				DB::table('tb1_online_member_loggin_try')
					->insert($loggin_try);

				if ($online_member_loggin_iid == 0) {
					$last_id = DB::getPdo()->lastInsertId();;
					DB::table('tb1_online_member_loggin_try')
						->where('id', '=', $last_id)
						->update(['parent_loggedin_id' => $last_id]);

					//echo 'get id:'.dd($last_id);
				}
				////}
				///end
				calculate_coc($user_id);


				return new Response(array("code" => 200, "status" => true, "status#" => "1", "data#" => $dataArr, "service_type#" => $userType, "user_type#" => $user_type, "CM_user_type#" => $CM_user_type, "show_manage_pref_screen#" => $show_manage_pref_screen), 200);
			} else {
				return new Response(array("code" => 401, "status" => false, "status#" => "1001", "message#" => "Unauthorized action. Wrong username/password"), 401);
				//abort(403, array( "status#" => "1001" , "message#" => "Unauthorized action. Token access denied"));

			}
		} else {
			return new Response(array("code" => 400, "status" => false, "status#" => "1011", "message#" => "Unauthorized action. please enter username and password"), 400);
			//abort(403, array( "status#" => "1011" , "message#" => "Unauthorized action. please enter username and password"));
		}
	}

	/**
	 * Generate a new token from refresh token.
	 * 
	 * @param  \Illuminate\Http\Request  $request
	 * @return \Illuminate\Http\Response
	 */
	public function token(Request $request)
	{
		//
		if ($request->has('refreshToken')) {
			$refreshToken = $request->input('refreshToken');
			$auth = new authentication();
			$token = $auth->generateToken($refreshToken);
			if ($token) {
				return new Response(array("code" => 200, "status" => true, "status#" => "1", "data#" => array("token" => $token)), 200);
			} else {
				return new Response(array("code" => 401, "status" => false, "status#" => "1001", "message#" => "Unauthorized action. Token access denied"), 401);
				//abort(403, array( "status#" => "1001" , "message#" => "Unauthorized action. Token access denied"));
			}
		} else {
			return new Response(array("code" => 400, "status" => false, "status#" => "1002", "message#" => "Unauthorized action. Please request with token"), 400);
			//abort(403, array( "status#" => "1002" , "message#" => "Unauthorized action. Please request with token"));

		}
	}
}
