<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Action\ccavenueValidator;
use App\Http\Controllers\Action\itunesReceiptValidator;
use App\Http\Controllers\Action\Payment;
use App\Http\Controllers\Action\PaypalValidator;
use App\Http\Controllers\Action\Tender;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;


use App\Http\Controllers\Controller;
use App\Http\Controllers\Action\Common ;

use Illuminate\Http\Response;
use App\Http\Controllers\Auth\authentication;
use App\Http\Controllers\Auth\User;
use Jenssegers\Agent\Agent;
//use ReceiptValidator\iTunes\Validator as iTunesValidator;
use DB;

class UserController extends Controller
{

    private $request = NULL;
    /**
     * Display user's information.
     * @param  \Illuminate\Http\Request     $request
     * @return \Illuminate\Http\Response
     */

    private $UserPlan = array(
        "MOBILE" => array(
            'title'=>'Mobile Application (Introductory Offer- 6 Months)',
            "plancode" => "MOBILE" ,
            'description'=>'Prices, News, Tender, Logistics, Email Alert, Reports. Free Add-on	of 6 months SMS alerts worth INR 3,000/-',
            'price'=>'12950',
            'you_get'=>'you_get desc2',
            "btn" => "Buy"
        )
);

    public function showProfile(Request $request)
    {
        if ($request->has('token'))
        {
            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);
            if ($user_id) {
                //Return profile data
//                echo $user_id;
                $user = new User($user_id);
                $user_data = $user->get($user_id)  ;
                if ( $user_data )
                    return new JsonResponse(array ( "status#"=> "1" ,"data#" => $user_data ) , 200 );
                else
                    return new JsonResponse(array ( "status#"=> "1001" ,"message#" => "No user data" ) , 200 );
            }
            else {
                return new JsonResponse( array( "status#" => "1001" , "message#" => "Unauthorized action. Token access denied") , 403 ) ;
            }
        }
        else {
            return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Please request with token") , 403 ) ;
        }

    }
    /**
     * create new user's .
     * @param  \Illuminate\Http\Request     $request
     * @return \Illuminate\Http\Response
     */
    public function createProfile( Request $request )
    {
        if (
            $request->has('password') && //
            $request->has('email') && //
            $request->has('company') && //
            $request->has('name') && //
            $request->has('phoneno') && //
            $request->has('country') //
//            $request->has('source_from') // we have to hardcode this thing from mobile.
        )
        {

            $user = new User();
            $username = $request->input('email') ;

            /**
             * For user agent
             */
            $source_from = 'mobileapp' ;

            /**
             * For IpAddress
             */
            $ipAddress = $_SERVER['REMOTE_ADDR'];
            if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
                $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
            }

            /**
             * If state is present
             */
            $state = null ;
            if ($request->has('state'))
            {
                $state = $request->input('state') ;
            }

            /**
             * Send request
             */
            $result = $user->create( $username ,
                                $request->input('password'),
                $request->input('email'),
                                $request->input('company'),
                                $request->input('name'),
                                $request->input('phoneno'),
                                "SteelMint Mobileapp",
                $request->input('country') ,
                $state,
                $ipAddress,
                $source_from ) ;
            $responce = '';
            $header = '';

            switch ($result) 
            {
                case "You Successfully Registered" :
                    # code...
                    // 
                    $header = 200;
                    $responce = array( "status#" => "1", "message#" => $result);
                    break;
                case "Email Verification needed" :
                    $header = 200;
                    $responce = array( "status#" => "1003", "message#" => $result);
                    break;
                case "Email Already exists" :
                    $header = 200;
                    $responce = array( "status#" => "1022", "message#" => $result);
                    break;
                default:
                    # code...
                    $header = 500;
                    $responce = array( "message#" => "Unexpected error", "status#" => "1024" );
                    break;
            }
            return new JsonResponse( $responce, $header );
        }
        else {
            abort(206, 'Partial input') ;
        }
    }

    /**
     * Update user's information.
     * @param  \Illuminate\Http\Request     $request
     * @return \Illuminate\Http\Response
     */
    public function updateProfile(Request $request)
    {
        $this->request = $request ;
        if ($request->has('token'))
        {
            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);
            if ($user_id) {
                $res = '';
                if ($request->has('password'))
                {
                    $res = $this->updateInput('password'   , $user_id) ;
                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 2:
                            return new JsonResponse( array("status#" => "1032" , "message#" => "please enter old password for new password " ));
                            break;

                        case 3:
                            return new JsonResponse( array("status#" => "1033" , "message#" => "email exists" ));
                            break;

                        case 4:

                            return new JsonResponse( array("status#" => "1034" , "message#" => "phone number exists" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 6:

                            return new JsonResponse( array("status#" => "1036" , "message#" => "old password doesn't match with existing password" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }

                }


                if ($request->has('email'))
                {
                    $res = $this->updateInput('email'   , $user_id) ;
                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 2:
                            return new JsonResponse( array("status#" => "1032" , "message#" => "please enter old password for new password " ));
                            break;

                        case 3:
                            return new JsonResponse( array("status#" => "1033" , "message#" => "email exists" ));
                            break;

                        case 4:

                            return new JsonResponse( array("status#" => "1034" , "message#" => "phone number exists" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 6:

                            return new JsonResponse( array("status#" => "1036" , "message#" => "old password doesn't match with exiting password" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }


                if ($request->has('phoneno'))
                {
                    $res = $this->updateInput('phoneno'   , $user_id) ;
                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 2:
                            return new JsonResponse( array("status#" => "1032" , "message#" => "please enter old password for new password " ));
                            break;

                        case 3:
                            return new JsonResponse( array("status#" => "1033" , "message#" => "email exists" ));
                            break;

                        case 4:

                            return new JsonResponse( array("status#" => "1034" , "message#" => "phone number exists" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 6:

                            return new JsonResponse( array("status#" => "1036" , "message#" => "old password doesn't match with exiting password" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }



                if ($request->has('name'))
                {
                    $res = $this->updateInput('name', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 2:
                            return new JsonResponse( array("status#" => "1032" , "message#" => "please enter old password for new password " ));
                            break;

                        case 3:
                            return new JsonResponse( array("status#" => "1033" , "message#" => "email exists" ));
                            break;

                        case 4:

                            return new JsonResponse( array("status#" => "1034" , "message#" => "phone number exists" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 6:

                            return new JsonResponse( array("status#" => "1036" , "message#" => "old password doesn't match with exiting password" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('company'))
                {
                    $res = $this->updateInput('company', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;
                        
                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('company_type'))
                {
                    $res = $this->updateInput('company_type', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('product_of_interest'))
                {
                    $res = $this->updateInput('product_of_interest', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('designation'))
                {
                    $res = $this->updateInput('designation', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('department'))
                {
                    $res = $this->updateInput('department', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('address'))
                {
                    $res = $this->updateInput('address', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('state'))
                {
                    $res = $this->updateInput('state', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('city'))
                {
                    $res = $this->updateInput('city', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('country'))
                {
                    $res = $this->updateInput('country', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('pin_code'))
                {
                    $res = $this->updateInput('pin_code', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                if ($request->has('website'))
                {
                    $res = $this->updateInput('website', $user_id);

                    switch ($res)
                    {

                        case 1:
//                        return new Response( array("status#" => "1" ));
                            break;

                        case 5:

                            return new JsonResponse( array("status#" => "1035" , "message#" => "field data empty" ));
                            break;

                        case 7:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;

                        default:

                            return new JsonResponse( array("status#" => "1037" , "message#" => "invalid update request" ));
                            break;
                    }
                }

                return new JsonResponse( array("status#" => "1" ));
            }
            else {
                return new JsonResponse( array( "status#" => "1001" , "message#" => "Unauthorized action. Token access denied") , 403 ) ;
            }
        }
        else {
            return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Please request with token") , 403 ) ;
        }
    }

    /**
     * @param Request $request
     * @return String Response
     * For user logout
     */
    public function logout(Request $request)
    {
        if ($request->has('token'))
        {
            $token = $request->input('token');
            $user = new User();
            $auth = new authentication();
            $user_id = $auth->authToken($token);

            if ($user->userLogout($user_id)) {
                /**
                 * De-register user from notification table
                 */
                DB::table('gcm_device')
                    ->where("user_id" , "=" , $request->input('user_id'))
                    ->update(["user_id" => '']);
                return new JsonResponse(array( "status#" => "1" , "message#" => "Successfully logout") , 200);

            }
            else {
                return new JsonResponse( array( "status#" => "1001" , "message#" => "Unauthorized action. Token access denied") , 403 ) ;
            }
        }
	else if ($request->has('username') && $request->has('password') )
	{
		$user = new User();
		if ( $user->userLogout_user_pass($request->input('username') , $request->input('password')) )	    
			return new JsonResponse( array( "status#" => "1" , "message#" => "Successfully logout") , 200 ) ;
		return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Please request with token") , 403 ) ;
	}
        else {
            return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Username/password not matched") , 403 ) ;
        }
    }

    /**
     * Remove user's profile.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function deleteProfile(Request $request )
    {
        if ($request->has('token'))
        {
            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);
            if ($user_id) {
                $user = new User();
                $user->delete($user_id, $request->input('password'));
                if ($user)
                    return new JsonResponse( array("status#" => "1"));
                else
                    return new JsonResponse( array("status#" => "1051", "message#", "Internal database error"), 500 );
            }
            else if ($user_id == 'NV')
            {
                return new JsonResponse( array( "status#" => "1003" , "message#" => "Unauthorized action. Email not verified") , 403 ) ;
            }
            else {
                return new JsonResponse( array( "status#" => "1001" , "message#" => "Unauthorized action. Token access denied") , 403 ) ;
            }
        }
        else {
            return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Please request with token") , 403 ) ;
        }
    }

    public function mailActivation(Request $request, $activation_id)
    {
        $user = new User();

        // activateMail
        switch ($user->activateMail($activation_id)) {
            case 0:
//             	return Redirect::away($_ENV['REDIRECT_URL']);
                return new JsonResponse( "Thank You for Registering With SteelMint \n You are now a verified user", 200 ) ;
                break;
            case 1:
                return new JsonResponse( "token not exists in our database" , 403 ) ;
                break;
            case 2:
                return new JsonResponse( "token exists but updating user table activation table problem" , 403 ) ;
                break;
            case 3:
                # code...
                return new JsonResponse( "internal error, token exists more than once", 403 ) ;
                break;

            case 4:
                # code...
                return new JsonResponse(  "internal error, token not able to delete" , 403 ) ;
                break;

            case 5:
                # code...
                return new JsonResponse( "verification table updation error" , 403 ) ;
                break;
            
            default:
                # code...
                return new JsonResponse( "internal error, token exists more than once" , 403 ) ;
                break;
        }
    }

    public function forgetPassword(Request $request)
    {
    	if($request->has('email'))
    	{
    		$user = new User();
    		if($user->forgetPassword($request->input('email')))
    		{
    			return new JsonResponse(array("status#" => "1", "message#" => "password generated and send to mail" ));
    		}

            return new JsonResponse(array("status#" => "1026", "message#" => "This is not a registered email id" ));
    		
    	}
    	return new JsonResponse(array("status#" => "1026", "message#" => "email id not given" ));
    }
    
    
    /**
     * Private function to check and update input.
     *
     * @param   String: $field (field value to update)
     *          String: $user_id (user's id)
     * @return \Illuminate\Http\Response
     */
    private function updateInput($field, $user_id )
    {
        if( $this->request->has($field) )
        {
            $user = new User();
            $old_pass = '';
            if ($this->request->has('old_password'))
            {
                $old_pass = $this->request->input('old_password');
            }
            return $user->updateEntry( $user_id , $field , $this->request->input($field), $old_pass  ) ;


        }
        return 7;
    }

    public function statecountry(Request $request)
    {
    	$country_id = false;
    	
		if ($request->has('country_id'))
        {
            $country_id = $request->input('country_id');
		}
        $common = new Common();
        return new JsonResponse(
            array(
                "status#"=> "1",
                "data#" => $common->getCountryState($country_id)
            )
        );
    }

    public function Listing()
    {
        $data = array();

        $data['company_type'] = DB::table('tbl_companytype' )
            ->select(DB::raw("name, CAST( `id` as CHAR) as id"))
//            ->select('name', 'CAST( id as CHAR )')
            ->get();

        $data['department'] = DB::table('tbl_department')
            ->select(DB::raw("name, CAST( `id` as CHAR) as id"))
//            ->select('name', 'id')
            ->get();

        $data['designation'] = DB::table('tbl_designation')
            ->select(DB::raw("name, CAST( `id` as CHAR) as id"))
//            ->select('name', 'id')
            ->get();

        $temp = DB::table('tbl_producttype')
            ->select('name', 'category')
            ->get();

        foreach( $temp as $tm)
        {
            if(!empty($tm['category']))
                $data['product_type'][$tm['category']][] = $tm['name'] ;
        }

        return new JsonResponse(array(
            "status#" => "1",
            "data#" => $data
        ));
    }

    public function UpdateUserPlanBeforePayemt(Request $request)
    {
        if($request->has('plancode'))
        {
            $user_id = null ;
            $email = null ;
            $city = '' ;
            $state = '';
//            echo "hey";

            /**
             * For IpAddress
             */
            $ipAddress = $_SERVER['REMOTE_ADDR'];
            if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
                $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
            }

//            $ipAddress = "8.8.8.8" ;

            if($request->has('city'))
                $city = $request->city ;

            if($request->has('state'))
                $state = $request->state ;

            $arr = array() ;

            if($request->has('token'))
            {
                $token = $request->input('token');
                $auth = new authentication();

                $user_id = $auth->authToken($token);
                if(!$user_id)
                    abort(403, "Unauthorized action. Token access denied") ;

                $us = new User() ;
                $user = $us->get($user_id) ;
                $email = $user[$_ENV['EMAIL']];
            }
            else if($request->has('name')
                && $request->has('email')
                && $request->has('company')
                    && $request->has('phoneno')
                    && $request->has('country')
                    && $request->has('password')
                )

            {

                $arr['tbl_members']=array(
                'date'=>$GLOBALS['currDateTime'],///yyyy-mm-dd format
                'email'=>$email,
                'company'=>$request->company,
                'name'=>$request->name,
                'phoneno'=>$request->phoneno,
                'comments'=>'SteelMint Mobileapp',
                'billing_name'=>$request->name ,
                'username'=>$request->email,
                'password'=>$request->password,
                'designation'=>'',
                'city'=>$city,
                'other_city'=>'',
                'state'=>$state,
                'pin_code'=>'',
                'country'=>$request->country,
                'ipaddress'=>$ipAddress
                );

            }
            else
            {
                abort(206, "Partial Input, Request with token or name, email, company, phoneno, country, password");
            }

            $src_from='online';
            $source='mobileapp';
            $require_srvc=$request->input('plancode');
            $memid=$user_id;
            $f_product='W';

            $isiphone = false ;
            if($request->has('iphone'))
                $isiphone = true ;

            $plan = array() ;
            $price = null ;
            $currency = null ;

            include ($_ENV['COMMON_ROOT_PATH'].'/reg_process_steps.php') ;

            if($isiphone)
            {
                $res['account'] = 'inapp' ;
                switch($request->input('plancode'))
                {
                    case 'com.steelmint.OneYear' :
                        $require_srvc = 'MOBILEAPP' ;
                        break;
                    case 'ios' :
                        $require_srvc = 'MOBILEAPP' ;
                        break;
                    default:
                        break;
                }

                if($request->has('price') && $request->has('currency') )
                {
                    $price = $request->input('price') ;
                    $res['currency'] = $request->input('currency') ;
                }
                else
                    abort(206, "Send price and currency") ;

            }
            else
            {
                $plan =  getSubscriptionPlan('mobileapp' , $user_id , '' , $ipAddress )['plan'] ;

                $price = $plan[$require_srvc]['price'] ;
                $res['currency'] = $plan[$require_srvc]['currency'] ;
            }

//            var_dump( $source );
//            var_dump($src_from);
//            var_dump($require_srvc);
//            var_dump($email);
//            var_dump($arr);
//            var_dump($f_product);
//            var_dump($price);
//            var_dump($ipAddress);

            $r = processPersonalDetails($source , $src_from , $require_srvc, $email , $arr , $f_product , $price, $ipAddress ) ;

            $res['log_id'] = $r['log_id'] ;
            $res['order_id'] = $r['order_id'] ;
            $res['type'] = 'user' ;
            $res['amount'] = $price ;
            $res['status'] = 'pending' ;

//            var_dump($r) ;
//            var_dump($res) ;

            DB::table('payment_log')->insert($res) ;

            if(!$isiphone)
            {
                $res['account'] = $r['payment_gateway'] ;
                $res['payment_gateway'] = $res['account'] ;
                $res['pymtredirectURL']  = $r['pymtURLToredirectTo'] ;
                $res['currency'] = 'INR' ;
                if($res['account'] == 'paypal')
                    $res['currency'] = 'USD' ;
            }

            unset($res['account']) ;
            unset($res['log_id']) ;
            unset($res['status']) ;
            unset($res['type']) ;

            if($isiphone)
            {
                unset($res['payment_gateway']) ;
                unset($res['account'] ) ;
//                unset( $res['currency'] ) ;
                unset($res['pymtredirectURL'] ) ;
            }

            if(!$request->has('token'))
                $res['user_id'] = $r["memid"] ;

            return new JsonResponse(array(
                "status#" => "1" ,
                "data#" => $res
            )) ;
        }
        else
            abort(206, "Partial Input, Please send with plancode");

    }

    public function UpdateUserPlanAfterPayemt(Request $request)
    {
        if($request->has('encResp'))
        {

            $payment_gateway = "CCAVENUE" ;
            $ccavenue = new ccavenueValidator();

            $amount = null ;
            $status = null ;
            $currency = null ;

            $res = $ccavenue->validator($request->input('encResp')) ;

            DB::table('payment_log')
                ->update(["payment_gateway_response" => json_encode($res['info'])] )
                ->where('order_id' , '=' , $res['info']['order_id'] )
                ->where('type', '=' , 'user') ;

            $payment_gateway = 'CCAVENUE' ;

            if($res['status'] == "success")
            {
//                echo "amount: $amount\tcurrency: $currency" ;
                $payment = new Payment( $amount , $currency , $payment_gateway, 'user', $user_id ) ;
                $res = $payment->verify_payment($request->input('order_id')) ;

                if($res == true )
                    return new JsonResponse(array(
                        "status#" => "1" ,
                        "message#" => "Payment successful"
                    )) ;
                else
                    return new JsonResponse(array(
                        "status#" => "1" ,
                        "data#" => $res['status']
                    )) ;
            }
            else
            {
                return new JsonResponse(array(
                    "status#" => "1012" ,
                    "message#" => "Payment status not completed"
                ));
            }

        }
        else if($request->has('order_id')
                && $request->has('payment_detail')
                && $request->has('status')
        )
        {
            $user_id = null;
            if($request->has('token'))
            {
                $token = $request->input('token');
                $auth = new authentication();

                $user_id = $auth->authToken($token);
                if(!$user_id)
                    abort(403, "Unauthorized action. Token access denied") ;

            }
            else if($request->has('user_id'))
            {

                $user_id = $request->user_id ;
            }
            else
            {
                abort(206, "Partial Input, Request with token or user_id");
            }

            $us = new User() ;
            $user = $us->get($user_id) ;
            $email = $user[$_ENV['EMAIL']];

            if(!$user_id)
                abort(403, "Unauthorized action. Token access denied") ;

            /**
             * Get payment detail from logs
             */
            $payment = DB::table('payment_log')
                ->select('log_id' , 'amount' , 'currency' , 'account as payment_gateway' )
                ->where('order_id' , '=' , $request->input('order_id') )
                ->first();

            include_once ($_ENV['COMMON_ROOT_PATH'].'/reg_process_steps.php') ;

            $memid=$user_id ;
            $reg_log_id=$request->input('log_id');
            $payment_details_arr=$request->input('payment_detail');// responce from payment page
            $order_status=$request->input('status');
            $mode='mobile';

            $amtPaidByUser = null ;
            $status = null ;
            $currency = null ;

            $gatewayUsedToMakePymt = null ;

            if(strcasecmp($order_status , 'success') == 0 )
            {
                if( strcasecmp($payment['payment_gateway'] , 'paypal' ) == 0)
                {
                    $gatewayUsedToMakePymt = 'paypal' ;

                    $paypal = new PaypalValidator() ;
                    $pay = $paypal->verifyPayment($request->input("payment_detail")) ;
                    $data = $pay->toArray() ;

                    DB::table('payment_log')
                        ->update(["payment_gateway_response" => json_encode($data)] )
                        ->where('order_id' , '=' , $request->input('order_id')  )
                        ->where('type', '=' , 'user') ;

                    if($data['intent'] == 'sale' && $data['state'] == 'approved' && $data['intent'] == 'sale')
                    {
                        $amtPaidByUser = $data['transactions'][0]['amount']['total'] ;
                        $status = $data['state'] ; //created; approved; failed; canceled; expired; pending.
                        $currency = $data['transactions'][0]['amount']['currency'] ;
                        $payment_details_arr = $data ;


                        $payment = new Payment( $amtPaidByUser , $currency , $gatewayUsedToMakePymt, 'user', $user_id, $payment_details_arr ) ;
                        $res = $payment->verify_payment( $request->input('order_id') ) ;

                        if($res == true ) {
                            return new JsonResponse(array(
                                "status#" => "1",
                                "message#" => "Payment successful"
                            ));
                        }
                        else
                            return new JsonResponse($res) ;
                    }
                    else
                        return new JsonResponse(array(
                            "status#" => "0" ,
                            "message#" => "Payment status not completed"
                        ));

                }

                elseif( strcasecmp( $payment['payment_gateway'] , 'INAPP' ) == 0)
                {
//                    echo "in inapp purchase" ;
                    $gatewayUsedToMakePymt = 'IN-APP' ;
                    $receipt = $request->input('payment_detail') ;
//                    $resp = $this->iphonePaymentValidate($receipt) ;

//                    DB::table('payment_log')
//                        ->update(["payment_gateway_response" => json_encode($resp)] )
//                        ->where('order_id' , '=' , $request->input('order_id')  )
//                        ->where('type', '=' , 'user') ;

                    $byte_written = \File::append('inapp_receipt.txt', var_export($request->all(), true ));
//                    var_dump($resp) ;

//                    echo "after validation" ;
                    $resp['success'] = $request->input('status') ;
                    if( !$resp['success'] )
                        $order_status = 'failed' ;
                    $payment_details_arr =  $resp['info'];

                    if($resp['success'])
                    {
                        $payment = new Payment( $amtPaidByUser , $currency , 'inapp' , 'user', $user_id, $payment_details_arr ) ;
                        $res = $payment->verify_payment( $request->input('order_id') ) ;

                        if($res == true )
                        {
                            DB::table('payment_log')
                                ->where('order_id' , '=' , $request->input('order_id') )
                                ->update(['status' => "success"]);
                            return new JsonResponse(array(
                                "status#" => "1" ,
                                "message#" => "Payment successful" ,
//                                "info" => $payment_details_arr
                            )) ;
                        }

                        else
                            return new JsonResponse($resp) ;
                    }
                    else
                        return new JsonResponse(array(
                            "status#" => "1310" ,
                            "message#" => "Payment status not completed"
                        ));
                }

                abort(500, "Not valid payment gateway") ;
            }
            else
            {
                DB::table('payment_log')
                    ->where('order_id' , '=' , $request->input('order_id') )
                    ->update(["status" => $order_status ]);
                return new JsonResponse(array(
                    "status#" => "1" ,
                    "message#" => "Payment Status: ".$order_status
                )) ;
            }



//            $return = processDetailsAfterPymt($memid, $reg_log_id, $payment_details_arr, $order_status, $mode , $gatewayUsedToMakePymt , $amtPaidByUser );

//            if($return['message'] == 'Payment done Succesfully')
//            {
//                DB::table('payment_log')
//                    ->where('log_id' , '=' , $reg_log_id )
//                    ->update(['status' => "success"]);
//            }

//            return new JsonResponse(array(
//                "status#" => "1" ,
//                "data#" => $return
//            )) ;
        }
        else
            abort(206, "Partial Input") ;
    }

    /**
     * Done
     * @param Request $request
     * @return JsonResponse
     */
    public function getSubscriptionPlan(Request $request)
    {
        $user_id = 0 ;
        if($request->has('token')
            && $request->has('plancode') ) {
            $token = $request->input('token');
            $auth = new authentication();

            $user_id = $auth->authToken($token);

            if(!$user_id)
                return new JsonResponse(array(
                    "status#" => "403" ,
                    "message#" => "Token unauthenticated"
                )) ;
        }

        include ($_ENV['COMMON_ROOT_PATH'].'/reg_process_steps.php') ;

        /**
         * For IpAddress
         */
        $ipAddress = $_SERVER['REMOTE_ADDR'];
        if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
            $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
        }

        $plan =  getSubscriptionPlan('mobileapp' , $user_id , '' , $ipAddress ) ;

        return new JsonResponse(array(
            "status#" => "1" ,
            "data#" => $plan
        )) ;

    }

    private function iphonePaymentValidate($receipt){
//        $validator = new iTunesValidator(iTunesValidator::ENDPOINT_SANDBOX);
//
//        try {
//            $response = $validator->setReceiptData($receipt)->validate();
//        } catch (Exception $e) {
////            echo 'got error = ' . $e->getMessage() . PHP_EOL;
//            $resp['status'] = false ;
//        }
//
//        $resp = array() ;
//
//        if ($response->isValid()) {
//
//            $resp['status'] = true ;
//            $resp['info'] = $response->getReceipt() ;
//
//        } else {
//            $resp['status'] = false ;
//            $resp['info'] = $response->getResultCode() ;
//        }
//
//        return $resp ;

    }
	
	public function PortfolioFilter(Request $request)
    {
        $user_id = 0 ;
		
        if($request->has('token') || $request->has('memid')
             ) {
			
			if($request->has('memid')){
				$memid = $request->input('memid');
				$memid = _encrypt_decrypt($action='decrypt', $memid);
				$auth = new authentication();
				$user_id = $auth->authUserId($memid);//for web user
			}else{
				$token = $request->input('token');
				$auth = new authentication();
				$user_id = $auth->authToken($token);
			}
			
            if(!$user_id)
                return new JsonResponse(array(
                    "status#" => "403" ,
                    "message#" => "Token unauthenticated"
                )) ;
        } else {
            return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Please request with token") , 403 ) ;
        }

		$type = '';
		if($request->has('token'))
			$type = $request->input('type');
		
		$data = array();
		
		
		$country = array('Asia & Asia-Pacific'=>array('India', 'China', 'Korea', 'Pakistan', 'Bangladesh', 'Nepal', 'Australia'),'South East Asia','Middle East & Africa','CIS Nations','Europe', 'America'=>array('US/Canada', 'China'), 'Global');
		$category = array('Iron Ore','Coal','Ferrous Scrap','Ship Breaking','Semi Finish','Finish Long','Finish Flat','Ferro Alloy');
		$news_category = array(111=>'Iron Ore',112=>'Coal',113=>'Ferrous Scrap',114=>'Ship Breaking',115=>'Semi Finish',116=>'Finish Long',117=>'Finish Flat',118=>'Ferro Alloy');
		$lead_type = array('Buy','Sell','Services');
		$pb_lead_type = array('Buy','Sell');
		
		if($type){
			$temp = DB::table('tbl_user_portfolio')
            ->select('type', 'row_id', 'prices_col','category', 'country', 'lead_type')
			->where('user_id', '=' , $user_id)
			->where('type', '=' , $type)
            ->get();
			
		}else{
			$temp = DB::table('tbl_user_portfolio')
            ->select('type', 'row_id', 'prices_col','category', 'country', 'lead_type')
			->where('user_id', '=' , $user_id)
            ->get();
		}
		
		foreach( $temp as $tm)
        {
            if($type=='prices')
			{
				$data[$tm['type']][$tm['prices_col']][] = $tm['row_id'];
				//$data[$tm['type']]['prices_col'][] = $tm['prices_col'];
			}
			else{
				 $data[$tm['type']]['category'] = explode(',',$tm['category']);
				 $data[$tm['type']]['country'] = explode(',',$tm['country']);
				 $data[$tm['type']]['lead_type'] = explode(',',$tm['lead_type']);
			}
        }
		
		$res=array();
		switch ($type) 
		{
			case "news" :
				foreach( $news_category as $_category_id=>$_category){
					if(in_array($_category_id, $data['news']['category']))
						$categoryFlag=1;
					else
						$categoryFlag=0;
					
						$res['news']['category'][] = array(
												'name'=>$_category,
												'cat_id'=>$_category_id,
												'flag'=>$categoryFlag,
												'parent'=>''
											);
				}
				
				foreach( $country as $key_country=>$_country){
					if(in_array($_country_1, $data['news']['country']))
									 $countryFlag=1;
								else
									$countryFlag=0;
						
						if(is_array($_country)){
							$res['news']['country'][] = array(
														'name'=>$key_country,
														'parent'=>'Y',
													); 
							foreach( $_country as $_country_1){
								if(in_array($_country_1, $data['news']['country']))
									 $countryFlag=1;
								else
									$countryFlag=0;
								$res['news']['country'][] = array(
														'name'=>$_country_1,
														'flag'=>$countryFlag,
														'parent'=>'N'
													);
							}
						}else{
							if(in_array($_country, $data['news']['country']))
								$countryFlag=1;
							else
								$countryFlag=0;
							$res['news']['country'][] = array(
													'name'=>$_country,
													'parent'=>'Y',
													'flag'=>$countryFlag
												);
						}
				}
			break;
			case "tenders" :
				foreach( $category as $_category){
					if(in_array($_category, $data['tenders']['category']))
						$categoryFlag=1;
					else
						$categoryFlag=0;
						$res['tenders']['category'][] = array(
												'name'=>$_category,
												'flag'=>$categoryFlag,
												'parent'=>''
											);
				}
				
				
				foreach( $lead_type as $_type){
						if(in_array($_country, $data['tenders']['lead_type']))
							 $typeFlag=1;
						else
							$typeFlag=0;
						$res['tenders']['lead_type'][] = array(
												'name'=>$_type,
												'flag'=>$typeFlag
											);
				}
			break;
			case "plantbee" :
				
				$plant_type = DB::table('plant_type')
					->select('plant_type_code', 'plant_type_name', 'level','parent_cat_code')
					->where('vstatus', '=' , 'enable')
					->where('level', '<=' , 2)
					->orderBy('parent_cat_code' , 'asc')
					->orderBy('plant_type_name' , 'asc')
					->get();
				$level1=array();
				$level2=array();
				foreach( $plant_type as $pt)
				{
					 $plant_type_code = $pt['plant_type_code'];
					 $plant_type_name = $pt['plant_type_name'];
					 $parent_cat_code = $pt['parent_cat_code'];
					 
					 if(in_array($plant_type_code, $data['plantbee']['category']))
							$countryFlag=1;
						else
							$countryFlag=0;
						
					 if($parent_cat_code!=''){
						
							$level2[$parent_cat_code][] = array(
												'name'=>$plant_type_name,
												'flag'=>$countryFlag,
												'plant_type_code'=>$plant_type_code
											);						
						
					 }else{
						
							$level1[] = array(
												'name'=>$plant_type_name,
												'flag'=>$countryFlag,
												'plant_type_code'=>$plant_type_code		
											);
					 }
				}
				
				foreach( $level1 as $k=>$arr){
					$res['plantbee']['category'][$k] = $arr;
					if(isset($level2[$arr['plant_type_code']]))
						$res['plantbee']['category'][$k]['sub_cat'] = $level2[$arr['plant_type_code']];
					else
						$res['plantbee']['category'][$k]['sub_cat'] = array();
				}
				foreach( $pb_lead_type as $_type){
						if(in_array($_country, $data['tenders']['lead_type']))
							 $typeFlag=1;
						else
							$typeFlag=0;
						$res['plantbee']['lead_type'][] = array(
												'name'=>$_type,
												'flag'=>$typeFlag
											);
				}
				
			break;
			case "prices" :
				$sterm =  htmlspecialchars($request->input('sterm'));
				$sterm = strtolower($sterm);			
				
				$repl = array('price'=>'', 'prices'=>'');
				$sterm = trim(strtr($sterm, $repl));
				$cond_dom='';$cond_exim='';
				
				if($sterm){
					$cond_exim .= " and (";
					$cond_exim .= " category like'%$sterm%' OR ";
					$cond_exim .= " sub_category like'%$sterm%' OR ";
					$cond_exim .= " item like'%$sterm%' OR ";
					$cond_exim .= " f_size like'%$sterm%' OR ";
					$cond_exim .= " f_grade like'%$sterm%' OR ";
					$cond_exim .= " delivery_terms like'%$sterm%' OR ";
					$cond_exim .= " particular like'%$sterm%' OR ";
					$cond_exim .= " cnf_fob like'%$sterm%' OR ";
					$cond_exim .= " chemical_composition like'%$sterm%' OR ";
					$cond_exim .= " payment like'%$sterm%' OR ";
					$cond_exim .= " quantity like'%$sterm%' OR ";
					$cond_exim .= " delivery_period like'%$sterm%' OR ";
					$cond_exim .= " taxes like'%$sterm%' OR ";
					$cond_exim .= " remarks like'%$sterm%' ";
					$cond_exim .= " ) ";
					
					$cond_dom .= " and (";
					$cond_dom .= " category like'%$sterm%' OR ";
					$cond_dom .= " sub_category like'%$sterm%' OR ";
					$cond_dom .= " item like'%$sterm%' OR ";
					$cond_dom .= " first_col like'%$sterm%' OR ";
					$cond_dom .= " region like'%$sterm%' OR ";
					$cond_dom .= " state like'%$sterm%' OR ";
					$cond_dom .= " city like'%$sterm%' OR ";
					$cond_dom .= " supplier like'%$sterm%' OR ";
					$cond_dom .= " chemical_composition like'%$sterm%' OR ";
					$cond_dom .= " delivery_terms like'%$sterm%' OR ";
					
					$cond_dom .= " payment like'%$sterm%' OR ";
					$cond_dom .= " quantity like'%$sterm%' OR ";
					$cond_dom .= " delivery_period like'%$sterm%' OR ";
					$cond_dom .= " taxes like'%$sterm%' OR ";
					$cond_dom .= " remarks like'%$sterm%'  ";
					$cond_dom .= " ) ";
				}
				
				/* 
				REPLACE(UPPER(concat(category, sub_category, item, first_col, region,state, city,supplier,chemical_composition, delivery_terms, payment, quantity, delivery_period, taxes, remarks)), ' ', '') as s_res
				
				$search_title_Arr = explode(" ", $sterm);
				if(count($search_title_Arr)>0){
					foreach($search_title_Arr as $key=> $_s_key){
						if(trim($_s_key)!='' ){
							if($_whr_1)
								$_whr_1.=' and ';
							$_s_key = str_replace(" ", "",$_s_key);
							$_whr_1.= ' s_res like UPPER("%'.$_s_key.'%") ';
							
						}
					}
				}
				if($_whr_1)
				{	
					$having =" having ".$_whr_1."";
				} */
				
				$price_list = DB::connection('mysql')
					->select(DB::raw("SELECT category, sub_category, `id`, `first_col`, CASE
						WHEN f_size <>'' and f_grade <> ''  THEN concat(f_size ,', ', f_grade)
						WHEN f_size <>'' THEN f_size
						WHEN f_grade <> '' THEN f_grade
					END	as second_col,
					'f' as prices_col FROM `tbl_dom_master`	where 1 $cond_dom
					union all 
					select category, sub_category, `id`,  concat('CNF ', unload_country) as first_col, CASE
						WHEN f_size <>'' and f_grade <> '' and load_country <> '' THEN concat(f_size ,', ', f_grade , ', ', load_country)
						WHEN f_size <>'' and load_country <> '' THEN concat(f_size , ', ', load_country)
						WHEN f_grade <> '' and load_country <> '' THEN concat(f_grade , ', ', load_country)
						WHEN f_size <> '' and load_country = '' THEN f_size
						WHEN f_grade <> '' and load_country = '' THEN f_grade
						WHEN f_size = '' and f_grade = '' and load_country <> '' THEN load_country
					END	as second_col, 'cnf' as prices_col 
					FROM `tbl_exim_master` where cnf_fob like '%CNF%' $cond_exim
					union all 
					select category, sub_category, `id`,  concat('FOB ', unload_country) as first_col, CASE
						WHEN f_size <>'' and f_grade <> ''  THEN concat(f_size ,', ', f_grade)
						WHEN f_size <>'' THEN f_size
						WHEN f_grade <> '' THEN f_grade
					END	as second_col, 'fob' as prices_col 
					FROM `tbl_exim_master` where cnf_fob like '%FOB%' $cond_exim
					order by category, sub_category, first_col, second_col
					")) ;
				$list = array();
				foreach($price_list as $price )
				{
					if(in_array($price['id'], $data['prices'][$price['prices_col']]))
						$categoryFlag=1;
					else
						$categoryFlag=0;
					
						$res[] = array(
												'row_id'=>$price['id'],
												'prices_col'=>$price['prices_col'],
												'flag'=>$categoryFlag,
												'first_col'=>$price['first_col'],
												'second_col'=>$price['second_col']			
											);
				}
			break;
			DEFAULT:
				foreach( $category as $_category){
					if(in_array($_category, $data['news']['category']))
						$categoryFlag=1;
					else
						$categoryFlag=0;
					
						$res['news']['category'][] = array(
												'name'=>$_category,
												'flag'=>$categoryFlag,
												'parent'=>''
											);
					if(in_array($_category, $data['tenders']['category']))
						$categoryFlag=1;
					else
						$categoryFlag=0;
						$res['tenders']['category'][] = array(
												'name'=>$_category,
												'flag'=>$categoryFlag,
												'parent'=>''
											);
				}
				
				foreach( $country as $_country){
						if(in_array($_country, $data['news']['country']))
							 $countryFlag=1;
						else
							$countryFlag=0;
						$res['news']['country'][] = array(
												'name'=>$_country,
												'flag'=>$countryFlag,
												'parent'=>''
											);
						if(in_array($_country, $data['tenders']['country']))
							 $countryFlag=1;
						else
							$countryFlag=0;
						$res['tenders']['country'][] = array(
												'name'=>$_country,
												'flag'=>$countryFlag,
												'parent'=>''
											);
				}
				
				foreach( $lead_type as $_type){
						if(in_array($_country, $data['tenders']['lead_type']))
							 $typeFlag=1;
						else
							$typeFlag=0;
						$res['tenders']['lead_type'][] = array(
												'name'=>$_type,
												'flag'=>$typeFlag,
												'parent'=>''
											);
				}
			break;
		}
				
        return new JsonResponse(array(
            "status#" => "1",
            "data#" => $res
        ));
    }
	
	public function updatePortfolioFilter(Request $request)
	{
		$user_id = 0 ;
		
        if(($request->has('token') || $request->has('memid'))
              && $request->has('type')) {
			
			$type = $request->input('type');
			
			if($request->has('memid')){
				$memid = $request->input('memid');
				$memid = _encrypt_decrypt($action='decrypt', $memid);
				$auth = new authentication();
				$user_id = $auth->authUserId($memid);//for web user
			}else{
				$token = $request->input('token');
				$auth = new authentication();
				$user_id = $auth->authToken($token);
			}
			
            if(!$user_id)
                return new JsonResponse(array(
                    "status#" => "403" ,
                    "message#" => "Token unauthenticated"
                )) ;
			
			if($type == 'prices'){
				$rows = $request->input('rows');
				
				foreach($rows as $_row){
					$row_id = $_row['row_id'];
					$prices_col = $_row['prices_col'];
					$flag = $_row['flag'];
					if($flag==0){
						DB::table('tbl_user_portfolio')
						->where('type', '=', 'prices' )
						->where('user_id', '=', $user_id )
						->where('prices_col', '=', $prices_col )
						->where('row_id', '=', $row_id )
						->delete();	
					}else{
						$ipAddress = $_SERVER['REMOTE_ADDR'];	
						DB::table('tbl_user_portfolio')->insert([ 'ip' => $ipAddress,
						'user_id' => $user_id,
						'type' => $type,
						'prices_col' => $prices_col,
						'row_id' => $row_id,
						'created_on' => $GLOBALS['currDateTime']]);
					}
				}
			}else{

				$category = !empty($request->input('category'))?$request->input('category'):'';
				$country = !empty($request->input('country'))?$request->input('country'):'';
				$lead_type = !empty($request->input('lead_type'))?$request->input('lead_type'):'';
				
				$result = DB::table('tbl_user_portfolio')
				->select('user_id')
				->where('user_id', '=', $user_id )
				->where('type', '=', $type )
				->get();

				if (count($result) > 0 )
				{
					//return false;
					DB::table('tbl_user_portfolio')
					->where('type', '=', $type )
					->where('user_id', '=', $user_id )
					->delete();	
				}
				
				$ipAddress = $_SERVER['REMOTE_ADDR'];	
				DB::table('tbl_user_portfolio')->insert([ 'ip' => $ipAddress,
				'user_id' => $user_id,
				'type' => $type,
				'category' => $category,
				'country' => $country,
				'row_id' => 0,
				'lead_type' => $lead_type,
				'created_on' => $GLOBALS['currDateTime']]);
				
			}
			
			return new JsonResponse(array(
				"status#" => "1",
				"message#" => "successfully updated"
			));
        } else {
            return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Please request with token") , 403 ) ;
        }
	}
}
