<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\TaskCount;
use App\Models\Users;
use App\Models\_Subscriptions;
use Validator;
use Illuminate\Support\Facades\Hash;
use JWTAuth, DB, GeoIP;
use Tymon\JWTAuth\Exceptions\JWTException;
use Carbon\Carbon;
use Mail;
use App\Mail\NotifyMail;
use App\Http\Controllers\Api\MyAuth;
use Illuminate\Mail\SentMessage;

class UserAuth extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'signup', 'reset_password', 'verify_otp', 'update_password']]);
        $this->guard = "api";
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {

        if ($json = MyAuth::Validation($request->data)) {
            $req = json_decode(base64_decode($json), true);

            if ($info = MyAuth::Validation($request->secure)) {
                $secure = json_decode(base64_decode($info), true);
            } else {

                return response()->json([
                    'code' => 404,
                    'message' => 'Invalid User Please Contact to Admin.',
                ]);
            }
            
            $xml=$req['xml'];
                        
            if($xml!=md5($req['email']."-".env('APP_PACKAGE_NAME')."-".$req['type'])){
                return $this->respError("Something went wrong invalid request");
            }
                   

            if ($req['type'] == "google") {

                $validator = Validator::make($req, [
                    'email' => 'required|email',
                    'person_id' => 'required|string|min:5',
                ]);
            } else {

                $validator = Validator::make($req, [
                    'email' => 'required|email',
                    'password' => 'required|string|min:5',
                ]);
            }


            if ($validator->fails()) {
               // return response()->json(['message' =>$validator->errors()->first(), 'code' => 401]);
                 return response()->json(['message' => "Something went wrong", 'code' => 401]);
            }

            if ($req['type'] == "google") {
                $user = Users::where(['email' => $req['email'], 'person_id' => $req['person_id']])->first();
            } else {
                $user = Users::where('email',$req['email'])->first();
            }

            if ($user) {
                
                if($req['type'] != "google"){
                    if (!Hash::check($req['password'], $user->password)) {
                        return response()->json([
                                'code' => 404,
                                'message' => 'Login credentials are invalid!.',
                            ]);
                    }
                }
                
                $task = TaskCount::where('user_id', $user->cust_id)->first();
                if (is_null($task)) {
                    DB::table('task_count')->insert(['user_id' => $user->cust_id]);
                }

                try {
                    if (!$token = JWTAuth::fromUser($user)) {

                        return response()->json([
                            'code' => 404,
                            'message' => $this->getResponseMsg('account_not_exist'),
                        ]);
                    }
                } catch (JWTException $e) {
                    return $credentials;
                    return response()->json([
                        'code' => 404,
                        'message' => 'Could not create token.'
                    ]);
                }
            } else {
                return response()->json([
                    'code' => 404,
                    'message' =>$this->getResponseMsg('account_not_exist'),
                ]);
            }

            $prevention = DB::table('fraud_prevention')->where('id', 1)->get();
            
            if ($secure['dup'] == 'true' && $prevention[0]->app_clonning == 'true') {
                return response()->json(['message' => $this->getResponseMsg('clone_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['emu'] == 'true' && $prevention[0]->block_emulator == 'true') {
                $this->logmonitor($user->cust_id, "Emulator Device Used.");
                return response()->json(['message' =>$this->getResponseMsg('emulator_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['term'] == 'true' && $prevention[0]->block_termux == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('termux_app_detected'), 'code' => 401]);
            }

            if ($secure['dm'] == 'false' && $prevention[0]->block_devMode == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('developer_mode_prevent'), 'code' => 401]);
            }

            if ($prevention[0]->vpn_required == 'true') {
                
                if($secure['npv'] != 'true'){
                    return response()->json(['message' => $prevention[0]->vpn_required_msg, 'code' => 401]);
                }
            }

            if ($secure['npv'] == 'true') {

                if ($prevention[0]->auto_banVpn == 'true') {
                    $this->logmonitor($user->cust_id, "VPN Used.");
                    $this->banuser($user->cust_id,$this->getResponseMsg('auto_ban_vpn_msg'));
                    return response()->json(['message' => $this->getResponseMsg('auto_ban_vpn_msg'), 'code' => 401]);
                }

                if ($prevention[0]->block_vpn == 'true') {
                    return response()->json(['message' =>$this->getResponseMsg('you_cant_use_vpn') , 'code' => 401]);
                }

                if ($prevention[0]->vpn_monitor == 'true') {
                    $this->logmonitor($user->cust_id, "VPN Used.");
                }
            }

            if ($secure['root'] == 'true') {
                $this->logmonitor($user->cust_id, "Rooted Device.");

                if ($prevention[0]->auto_banroot == 'true') {
                    $this->banuser($user->cust_id,$this->getResponseMsg('auto_ban_root_msg'));
                    return response()->json(['message' =>$this->getResponseMsg('auto_ban_root_msg'), 'code' => 401]);
                }

                if ($prevention[0]->block_root_device == 'true') {
                    return response()->json(['message' =>$this->getResponseMsg('root_prevent_msg'), 'code' => 401]);
                }
            }
           

            
            
            if($req['p_token']!=null && $user->p_token!=$req['p_token']){
                $user->p_token=$req['p_token'];
                $user->save();
            }
        
            if ($user->status == 1) {
                return response()->json(['message' => $user->reason, 'code' => 401]);
            }

            if ($user->updated_at != date('Y-m-d')) {
                Users::where('cust_id', $user->cust_id)->update(['updated_at' => date('Y-m-d')]);
            }

            // Get the token
            return $this->createNewTokenGoogle($user, $token);
        }

        return response()->json([
            'code' => 404,
            'message' => 'Invalid User Please Contact to Admin.',
        ]);
    }


    public function signup(Request $request)
    {
        if ($json = MyAuth::Validation($request->data)) {
            $req = json_decode(base64_decode($json), true);

            if ($info = MyAuth::Validation($request->secure)) {
                $secure = json_decode(base64_decode($info), true);
            } else {

                return response()->json([
                    'code' => 404,
                    'message' => 'Invalid User Please Contact to Admin.',
                ]);
            }
            
            $email=$req['type'];
            
            if(DB::table('delete_account')->where('email', $email)->count()>0){
                return response()->json(['message' => $this->getResponseMsg('delete_account_unlink_message'), 'code' => 401]);
            }

            if ($req['type'] == "google") {
                return $this->Googleregister($req, $secure);
            }
            

            $validator = Validator::make($req, [
                'name' => 'required|string|between:4,15|regex:/^[\w ]+$/|unique:customer',
                'email' => 'required|string|email|max:40|unique:customer',
                'password' => 'required|string|min:6'
            ]);

            if ($validator->fails()) {
                return response()->json(['message' => $validator->errors()->first(), 'code' => 401]);
            }

            geoip()->getLocation(null);
            $ip = UserAuth::getUserIpAddr();
            $arr_ip = geoip()->getLocation($ip);

            $prevention = DB::table('fraud_prevention')->where('id', 1)->get();

            if ($prevention[0]->block_country == 'true' && $prevention[0]->block_country_iso != null) {
                $iso = $prevention[0]->block_country_iso;
                $ar = explode(",", $iso);
                if (in_array($arr_ip->iso_code, $ar)) {
                    return response()->json(['message' => $prevention[0]->block_country_msg, 'code' => 401]);
                }
            }


            $cdip = Users::where('ip', $ip)->count();
            if ($cdip >= $prevention[0]->oneip_device) {
                return response()->json(['message' => $this->getResponseMsg('account_create_limit_reached'), 'code' => 401]);
            }

            if ($prevention[0]->onedevice == 'true') {
                if ($cd = Users::where('token', $secure['token'])->select('email')->first()) {
                    return response()->json(['message' => $this->getResponseMsg('account_exist_with').' ' . $cd->email, 'code' => 401]);
                }
            }

            
            
            if ($secure['dup'] == 'true' && $prevention[0]->app_clonning == 'true') {
                return response()->json(['message' => $this->getResponseMsg('clone_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['emu'] == 'true' && $prevention[0]->block_emulator == 'true') {
                $this->logmonitor($user->cust_id, "Emulator Device Used.");
                return response()->json(['message' =>$this->getResponseMsg('emulator_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['term'] == 'true' && $prevention[0]->block_termux == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('termux_app_detected'), 'code' => 401]);
            }

            if ($secure['dm'] == 'false' && $prevention[0]->block_devMode == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('developer_mode_prevent'), 'code' => 401]);
            }

            if ($secure['root'] == 'true' && $prevention[0]->block_root_device == 'true') {
                return response()->json(['message' => $this->getResponseMsg('root_prevent_msg'), 'code' => 401]);
            }
            
            
            $setting = DB::table('tbl_app_setting')->where('id', 1)->select('welcome_bonus')->get();

            $user               =       new Users;
            $user->name         =       $req['name'];
            $user->email        =       $req['email'];
            $user->token        =       $secure['token'];
            $user->p_token      =       $req['p_token'];
            $user->password     =       Hash::make($req['password']);
            $user->type         =       "email";
            $user->refferal_id  =       UserAuth::genUserCode();
            $user->ip           =       $ip;
            $user->country      =       $arr_ip->iso_code;
            
            if($setting[0]->welcome_bonus > 0){
                $user->balance  =      $setting[0]->welcome_bonus;
            }
            
            $res_user = $user->save();
            
            if($setting[0]->welcome_bonus > 0){
                DB::table('transaction')->insert([
                        'tran_type' => 'credit',
                        'type' => 'Welcome Bonus',
                        'user_id' =>  $user->cust_id,
                        'amount' => $setting[0]->welcome_bonus,
                        'ip' => $this->getUserIpAddr(),
                        'remained_balance' => $setting[0]->welcome_bonus,
                        'remarks' => $this->getResponseMsg('welcome_bonus'),
                        'inserted_at' => Carbon::now()
                    ]);
            }
            
            DB::table('task_count')->insert(['user_id' => $user->cust_id]);
                
            


            return response()->json([
                'message' =>$this->getResponseMsg('account_created_success_login_now') , 'code' => 201
            ]);
        }

        return response()->json([
            'code' => 404,
            'message' => 'Invalid User Please Contact to Admin.',
        ]);
    }

    public function googlelogin($req, $secure)
    {
        $validator = Validator::make($req, [
            'email' => 'required|string|email|max:100',
        ]);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first(), 'code' => 401]);
        }
        $user = Users::where(['person_id' => $req['person_id'], 'email' => $req['email']])->first();

        if ($user) {

            $task = TaskCount::where('user_id', $user->cust_id)->first();
            if (is_null($task)) {
                DB::table('task_count')->insert(['user_id' => $user->cust_id]);
            }

            try {
                if (!$token = JWTAuth::fromUser($user)) {
                    return response()->json([
                        'code' => 401,
                        'message' => $this->getResponseMsg('wrong_login_credential'),
                    ]);
                }
            } catch (JWTException $e) {
                return $credentials;
                return response()->json([
                    'code' => 401,
                    'message' => 'Could not create.',
                ]);
            }

            $prevention = DB::table('fraud_prevention')->where('id', 1)->get();

            if ($secure['dup'] == 'true' && $prevention[0]->app_clonning == 'true') {
                return response()->json(['message' => $this->getResponseMsg('clone_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['emu'] == 'true' && $prevention[0]->block_emulator == 'true') {
                $this->logmonitor($user->cust_id, "Emulator Device Used.");
                return response()->json(['message' =>$this->getResponseMsg('emulator_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['term'] == 'true' && $prevention[0]->block_termux == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('termux_app_detected'), 'code' => 401]);
            }

            if ($secure['dm'] == 'false' && $prevention[0]->block_devMode == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('developer_mode_prevent'), 'code' => 401]);
            }

            if ($prevention[0]->vpn_required == 'true') {
                
                if($secure['npv'] != 'true'){
                    return response()->json(['message' => $prevention[0]->vpn_required_msg, 'code' => 401]);
                }
            }

            if ($secure['npv'] == 'true') {

                if ($prevention[0]->auto_banVpn == 'true') {
                    $this->logmonitor($user->cust_id, "VPN Used.");
                    $this->banuser($user->cust_id,$this->getResponseMsg('auto_ban_vpn_msg'));
                    return response()->json(['message' => $this->getResponseMsg('auto_ban_vpn_msg'), 'code' => 401]);
                }

                if ($prevention[0]->block_vpn == 'true') {
                    return response()->json(['message' =>$this->getResponseMsg('you_cant_use_vpn') , 'code' => 401]);
                }

                if ($prevention[0]->vpn_monitor == 'true') {
                    $this->logmonitor($user->cust_id, "VPN Used.");
                }
            }

            if ($secure['root'] == 'true') {
                $this->logmonitor($user->cust_id, "Rooted Device.");

                if ($prevention[0]->auto_banroot == 'true') {
                    $this->banuser($user->cust_id,$this->getResponseMsg('auto_ban_root_msg'));
                    return response()->json(['message' =>$this->getResponseMsg('auto_ban_root_msg'), 'code' => 401]);
                }

                if ($prevention[0]->block_root_device == 'true') {
                    return response()->json(['message' =>$this->getResponseMsg('root_prevent_msg'), 'code' => 401]);
                }
            }


            if ($user->status == 1) {
                return response()->json(['message' => $user->reason, 'code' => 401]);
            }
            if ($user->updated_at != date('Y-m-d')) {
                Users::where('cust_id', $user->cust_id)->update(['updated_at' => Carbon::now()]);
            }

            return $this->createNewTokenGoogle($user, $token);
        } else {
            return response()->json([
                'code' => 401,
                'message' => $this->getResponseMsg('wrong_login_credential'),
            ]);
        }
    }

    public function Googleregister($req, $secure)
    {
        $validator = Validator::make($req, [
            'email' => 'required|string|email|max:100|unique:users',
        ]);


        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()->first(), 'code' => 401]);
        }
        if ($user = Users::where(['person_id' => $req['person_id'], 'email' => $req['email']])->first()) {

            try {
                if (!$token = JWTAuth::fromUser($user)) {
                    return response()->json([
                        'code' => 401,
                        'message' =>$this->getResponseMsg('wrong_login_credential'),
                    ]);
                }
            } catch (JWTException $e) {
                return $credentials;
                return response()->json([
                    'code' => 401,
                    'message' => 'Could not create.',
                ]);
            }


            $prevention = DB::table('fraud_prevention')->where('id', 1)->get();

            if ($secure['dup'] == 'true' && $prevention[0]->app_clonning == 'true') {
                return response()->json(['message' => $this->getResponseMsg('clone_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['emu'] == 'true' && $prevention[0]->block_emulator == 'true') {
                $this->logmonitor($user->cust_id, "Emulator Device Used.");
                return response()->json(['message' =>$this->getResponseMsg('emulator_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['term'] == 'true' && $prevention[0]->block_termux == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('termux_app_detected'), 'code' => 401]);
            }

            if ($secure['dm'] == 'false' && $prevention[0]->block_devMode == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('developer_mode_prevent'), 'code' => 401]);
            }

            if ($prevention[0]->vpn_required == 'true') {
                
                if($secure['npv'] != 'true'){
                    return response()->json(['message' => $prevention[0]->vpn_required_msg, 'code' => 401]);
                }
            }

            if ($secure['npv'] == 'true') {

                if ($prevention[0]->auto_banVpn == 'true') {
                    $this->logmonitor($user->cust_id, "VPN Used.");
                    $this->banuser($user->cust_id,$this->getResponseMsg('auto_ban_vpn_msg'));
                    return response()->json(['message' => $this->getResponseMsg('auto_ban_vpn_msg'), 'code' => 401]);
                }

                if ($prevention[0]->block_vpn == 'true') {
                    return response()->json(['message' =>$this->getResponseMsg('you_cant_use_vpn') , 'code' => 401]);
                }

                if ($prevention[0]->vpn_monitor == 'true') {
                    $this->logmonitor($user->cust_id, "VPN Used.");
                }
            }

            if ($secure['root'] == 'true') {
                $this->logmonitor($user->cust_id, "Rooted Device.");

                if ($prevention[0]->auto_banroot == 'true') {
                    $this->banuser($user->cust_id,$this->getResponseMsg('auto_ban_root_msg'));
                    return response()->json(['message' =>$this->getResponseMsg('auto_ban_root_msg'), 'code' => 401]);
                }

                if ($prevention[0]->block_root_device == 'true') {
                    return response()->json(['message' =>$this->getResponseMsg('root_prevent_msg'), 'code' => 401]);
                }
            }

            if ($user->status == 1) {
                return response()->json(['message' => $user->reason, 'code' => 401]);
            }

            if ($user->updated_at != date('Y-m-d')) {
                Users::where('cust_id', $user->cust_id)->update(['updated_at' => Carbon::now()]);
            }

            $task = TaskCount::where('user_id', $user->cust_id)->first();
            if (is_null($task)) {
                DB::table('task_count')->insert(['user_id' => $user->cust_id]);
            }

            return $this->createNewTokenGoogle($user, $token);
        } else {

            $validator = Validator::make($req, [
                'name' => 'required|string|between:4,100',
                'email' => 'required|string|email|max:100|unique:users',
            ]);


            if ($validator->fails()) {
                return response()->json(['message' => $validator->errors()->first(), 'code' => 401]);
            }

            geoip()->getLocation(null);
            $ip = UserAuth::getUserIpAddr();
            $arr_ip = geoip()->getLocation($ip);

            $prevention = DB::table('fraud_prevention')->where('id', 1)->get();
            if ($prevention[0]->block_country == 'true' && $prevention[0]->block_country_iso != null) {
                $iso = $prevention[0]->block_country_iso;
                $ar = explode(",", $iso);
                if (in_array($arr_ip->iso_code, $ar)) {
                    return response()->json(['message' => $prevention[0]->block_country_msg, 'code' => 401]);
                }
            }

            $cdip = Users::where('ip', $ip)->count();
            if ($cdip >= $prevention[0]->oneip_device) {
                return response()->json(['message' => $this->getResponseMsg('account_create_limit_reached'), 'code' => 401]);
            }

            if ($prevention[0]->onedevice == 'true') {
                if ($cd = Users::where('token', $secure['token'])->select('email')->first()) {
                    return response()->json(['message' =>$this->getResponseMsg('account_exist_with').' ' . $cd->email, 'code' => 401]);
                }
            }


            if ($secure['dup'] == 'true' && $prevention[0]->app_clonning == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('clone_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['emu'] == 'true' && $prevention[0]->block_emulator == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('emulator_app_prevent_msg'), 'code' => 401]);
            }

            if ($secure['term'] == 'true' && $prevention[0]->block_termux == 'true') {
                return response()->json(['message' => $this->getResponseMsg('termux_app_detected'), 'code' => 401]);
            }

            if ($secure['dm'] == 'true' && $prevention[0]->block_devMode == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('developer_mode_prevent'), 'code' => 401]);
            }

            if ($secure['root'] == 'true' && $prevention[0]->block_root_device == 'true') {
                return response()->json(['message' =>$this->getResponseMsg('root_prevent_msg'), 'code' => 401]);
            }
            
            $setting = DB::table('tbl_app_setting')->where('id', 1)->select('welcome_bonus', 'refer_mode','refer_join_bonus','refer_bonus')->get();

            

            $user               =       new Users;
            $user->name         =       $req['name'];
            $user->email        =       $req['email'];
            $user->token        =       $secure['token'];
            $user->person_id    =       $req['person_id'];
            $user->profile      =       $secure['profile'];
            $user->p_token      =       $req['p_token'];
            $user->type         =       "google";
            $user->refferal_id  =       UserAuth::genUserCode();
            $user->ip           =       $ip;
            $user->country      =       $arr_ip->iso_code;
            if($setting[0]->welcome_bonus > 0){
                $user->balance  =      $setting[0]->welcome_bonus;
            }
            
            $user->save();
            
            if($setting[0]->welcome_bonus > 0){
                DB::table('transaction')->insert([
                        'tran_type' => 'credit',
                        'type' => 'Welcome Bonus',
                        'user_id' =>  $user->cust_id,
                        'amount' => $setting[0]->welcome_bonus,
                        'ip' => $this->getUserIpAddr(),
                        'remained_balance' => $setting[0]->welcome_bonus,
                        'remarks' => $this->getResponseMsg('welcome_bonus'),
                        'inserted_at' => Carbon::now()
                    ]);
            }

            $task = TaskCount::where('user_id', $user->cust_id)->first();
            if (is_null($task)) {
                DB::table('task_count')->insert(['user_id' => $user->cust_id]);
            }
         

            $usr = Users::where('cust_id', $user->cust_id)->first();
            try {
                if (!$token = JWTAuth::fromUser($usr)) {
                    return response()->json([
                        'code' => 401,
                        'message' =>$this->getResponseMsg('wrong_login_credential') ,
                    ]);
                }
            } catch (JWTException $e) {
                return $credentials;
                return response()->json([
                    'code' => 401,
                    'message' => 'Could not create.',
                ]);
            }

            if ($user->updated_at != date('Y-m-d')) {
                Users::where('cust_id', $user->cust_id)->update(['updated_at' => Carbon::now()]);
            }
            return $this->createNewTokenGoogle($usr, $token);
        }
    }

    protected function createNewTokenGoogle($user, $token)
    {
        
        $cnt=DB::table('user_statistics')->where(['country_iso'=>$user->country,'user_id'=>$user->cust_id,'date'=>date('Y-m-d')])->count();
            
            if($cnt==0){
                DB::table('user_statistics')->insert(['country_iso'=>$user->country,'user_id'=>$user->cust_id,'ip'=>UserAuth::getUserIpAddr(),'date'=>date('Y-m-d'),'created_at'=>Carbon::now()]);
            }
        return response()->json([
            'resp' => $token . $user->refferal_id,
            'user' => [
                'cust_id'=>$user->cust_id,
                'person_id'=>$user->person_id,
                'name'=>$user->name,
                'profile'=>$user->profile,
                'balance'=>$user->balance,
                'refferal_id'=>$user->refferal_id,
                'from_refferal_id'=>$user->from_refferal_id,
                'email'=>$user->email,
                'xp'=>$user->xp,
                'level'=>$user->level,
                ],
            'message' => 'Login Successfull',
            'code' => 201,
            'noti' => $this->notiCount($user->cust_id)
        ]);
    }


    public function getUserIpAddr()
    {
        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if (isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;
    }

    public function genUserCode()
    {
        $this->refferal_id = [
            'refferal_id' => mt_rand(123456, 999999)
        ];

        $rules = ['refferal_id' => 'unique:customer'];

        $validate = Validator::make($this->refferal_id, $rules)->passes();

        return $validate ? $this->refferal_id['refferal_id'] : $this->genUserCode();
    }

    function banuser($userid, $reason)
    {
        $user = Users::find($userid);
        $user->status = 1;
        $user->balance = 0;
        $user->reason = $reason;
        $user->banned_time = Carbon::now();
        $user->save();
        DB::table('monitor_report')->insert(['userid' => $userid, 'type' => 'Acctoun Ban','remark'=>$reason]);
    }

    function logmonitor($userid, $type)
    {
        DB::table('monitor_report')->insert(['userid' => $userid, 'type' => $type]);
    }

    public function logout()
    {
        auth()->logout();
        return response()->json(['message' => 'User successfully signed out']);
    }

    public function refresh()
    {
        return $this->createNewToken(auth()->refresh());
    }

    public function userProfile()
    {

        return response()->json(auth()->user());
    }

    public function accountHistory($id)
    {
        $data = DB::table('transaction')->where('user_id',$id)->orderBy('id', 'DESC')->select('tran_type', 'type', 'amount', 'remarks', 'inserted_at')->limit(40)->get();
        return response()->json($data);
    }

    public function rewardHistory($id)
    {
        $data = DB::table('recharge_request')->where('user_id',$id)->orderBy('request_id', 'DESC')->select('request_id', 'mobile_no', 'type', 'amount', 'updated_at', 'status', 'remarks', 'date')->limit(10)->get();
        return response()->json($data);
    }

    public function guard()
    {
        return Auth::guard();
    }



    public function IpAddr()
    {
        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if (isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;
    }

    function notiCount($id)
    {
       // $global=DB::table('tbl_noti')->where(['noti_type' =>1])->whereDate('created_at',date('Y-m-d'))->count();    
        $usr=DB::table('tbl_noti')->where(['user_id' => $id, 'noti_type' => 0, 'status' => 0])->count();
        return $usr;
    }

    public function reset_password(Request $req)
    {

        if ($req->type == "reset") {
            $appname = config('app.name');
            $valideator = Validator::make($req->all(), [
                'email'    => 'email|exists:customer'
            ], [
                'email.email' => 'Enter Valid Email !',
                'email.exists' => 'Email Not Found !'
            ]);


            if ($valideator->fails()) {
                return response()->json(['msg' => $valideator->errors()->first(), 'code' => 404]);
            }

            $cnt = DB::table('customer')->where('email', $req->email)->get()->first()->type;
            if ($cnt == "google") {
                return response()->json(['msg' => $this->getResponseMsg('account_linked_with_google'), 'code' => 404]);
            }


            $otp = mt_rand(1234, 9999);

            $details = [
                'title' => $appname,
                'body' => 'Your Password Reset OTP is ' . $otp
            ];
            Mail::to($req->email)->send(new NotifyMail($details));
            DB::table('password_reset')->insert(
                ['email' => $req->email, 'token' => '', 'otp' => $otp]
            );

            return response(['code' => 201, 'msg' => $this->getResponseMsg('otp_has_been_sent')]);
        } else {
            $appname = config('app.name');
            $valideator = Validator::make($req->all(), [
                'email'    => 'email|exists:customer'
            ], [
                'email.email' => 'Enter Valid Email !',
                'email.exists' => 'Email Not Found !'
            ]);

            if ($valideator->fails()) {
                return response()->json(['msg' => $valideator->errors()->first(), 'code' => 404]);
            }

            $otp = mt_rand(1234, 9999);

            $details = [
                'title' => $appname,
                'body' => 'Your Email Verification OTP is ' . $otp
            ];
            Mail::to($req->email)->send(new NotifyMail($details));
            DB::table('password_reset')->insert(
                ['email' => $req->email, 'token' => '', 'otp' => $otp]
            );

            return response(['code' => 201, 'msg' => $this->getResponseMsg('otp_has_been_sent')]);
        }
    }


    public function verify_otp(Request $req)
    {
        $otp = $req->otp;
        $dataotp = DB::table('password_reset')->where('email', $req->email)->orderBy('id', 'DESC')->limit(1)->get()->first()->otp;

        if ($otp == $dataotp) {
            return response()->json(['code' => 201, 'msg' => 'Otp verified']);
        } else {
            return response()->json(['code' => 400, 'msg' => 'Wrong OTP']);
        }
    }

    public function update_password(Request $req)
    {
        $data = Users::where('email', $req->email)->get();
        $userid = $data[0]->cust_id;

        $otp = $req->otp;
        $dataotp = DB::table('password_reset')->where('email', $req->email)->orderBy('id', 'DESC')->limit(1)->get()->first()->otp;

        if ($otp != $dataotp) {
            return response()->json(['code' => 400, 'msg' => 'Wrong OTP']);
        }

        $update = Users::find($userid);
        $update->password = Hash::make($req->password);
        $update->save();
        if ($update) {
            return response()->json(['msg' => $this->getResponseMsg('password_update_succesfully'), 'code' => 201]);
        } else {
            return response()->json(['msg' => 'Error to Update Password', 'code' => 400]);
        }
    }
    
    function getResponseMsg($key){
        $lang=(request()->header('lang')==null || request()->header('lang')=='') ? 'en' : request()->header('lang');
        return DB::table('lang_text')->where(['lang'=>$lang,'txt_key'=>$key])->get()->first()->txt_value;
    }

}
