<?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 UserControllerTest 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 ) ;
        }

    }
    public function showProfile_old(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)
    {
        if(!$request->has('token')) {
            return new JsonResponse(array("status#" => "0" , "message#" => "Unauthorized action. Please request with token"), 200);
        }

        $token = $request->input('token');
        $user = new User();
        $auth = new authentication();
        $user_id = $auth->authToken($token);

        if(!$user_id) {
            return new JsonResponse(array("status#" => "0" , "message#" => "Unauthorized action"), 200);
        }

        $data = array();

        if($request->has('name')) {
            if(!empty($request->input('name'))) {
                $data['name'] = $request->input('name');
            } else {
                return new JsonResponse(array("status#" => "0" , "message#" => "Name must not be empty!"), 200);
            }
        }

         if($request->has('phoneno')) {
            if(!empty($request->input('phoneno'))) {

                $result = DB::table('tbl_members')
                    ->select('send_sms_to')
                    ->where('id', '=', $user_id)
                    ->first();

                if(isset($result['send_sms_to']) && $result['send_sms_to'] == 'R') {
                    $data['phoneno'] = $request->input('phoneno');
                } else {
                    $data['alternate_mob_no'] = $request->input('phoneno');
                }
                
            } else {
                return new JsonResponse(array("status#" => "1004" , "message#" => "Phone no. must not be empty!"), 400);
            }
        } 

        if($request->has('address')) {
            if(!empty($request->input('address'))) {
                $data['address'] = $request->input('address');
            } else {
                return new JsonResponse(array("status#" => "0" , "message#" => "Address must not be empty!"), 200);
            }
        }

        if($request->has('location')) {
            if(!empty($request->input('location'))) {
                $location = explode(",", $request->input('location'));
                $data['city'] = 0;
                $data['state'] = 0;
                $data['country'] = 0;

                if(isset($location[0])) {
                    $data['city'] = $location[0];
                }

                if(isset($location[1])) {
                    $data['state'] = $location[1];
                }

                if(isset($location[2])) {
                    $data['country'] = $location[2];
                }

            } else {
                return new JsonResponse(array("status#" => "1006" , "message#" => "Please select location!"), 200);
            }
        }

        if($request->has('pin_code')) {
            if(!empty($request->input('pin_code'))) {
                $data['pin_code'] = $request->input('pin_code');
            } else {
                return new JsonResponse(array("status#" => "0" , "message#" => "Pincode must not be empty!"), 200);
            }
        }

        if($request->has('designation')) {
            if(!empty($request->input('designation'))) {
                $data['job_title'] = $request->input('designation');
            } else {
                return new JsonResponse(array("status#" => "0" , "message#" => "Designation must not be empty!"), 200);
            }
        }

        if($request->has('profile_pic')) {
			$str= str_replace('\\','',$request->input('profile_pic'));
			$str= str_replace(' ','+',$str);
			$str = base64_decode($str);

			file_put_contents("/home/steelmin/public_html/images/clients/" . $user_id . ".png", $str);           
			$data['profile_pic'] = $user_id . ".png";
		}

        if($request->has('protype')) {
            $data['protype'] = $request->input('protype');
        } else {
            $data['protype'] = "";
        }

        if($request->has('company')) {
            $data['company'] = $request->input('company');
        }

        if($request->has('company_profile')) {
            $data['company_profile'] = $request->input('company_profile');
        }

        if($request->has('companytype')) {
            $data['companytype'] = $request->input('companytype');
        }

        $isd_code = array();

        if($request->has('isd_code')) {
            $isd_code = explode(" ", htmlspecialchars($request->input('isd_code'), ENT_QUOTES));
            $data['isd_code'] = end($isd_code);
        }

        if($data) {
            DB::table('tbl_members')
                ->where('id', $user_id)
                ->update($data);
        }

        return new JsonResponse(array("status#" => "1" , "message#" => "Profile updated successfully!"), 200);

    }	
	
    /**
     * change user's password in tbl_members
     * @param  \Illuminate\Http\Request     $request
     * @return \Illuminate\Http\Response
     */
    public function updatePassword(Request $request)
    {
        if(!$request->has('token')) {
            return new JsonResponse(array("status#" => "0" , "message#" => "Unauthorized action. Please request with token"), 200);
        }

        $token = $request->input('token');
        $user = new User();
        $auth = new authentication();
        $user_id = $auth->authToken($token);

        if(!$user_id) {
            return new JsonResponse(array("status#" => "0" , "message#" => "Unauthorized action"), 200);
        }

        $oldPassword = '';
        $newPassword = '';
        $repeatPassword = '';

        if(!$request->has('old_password') || empty($request->has('old_password'))) {
            return new JsonResponse(array("status#" => "0" , "message#" => "Invalid old password!"), 200);
        }

        if(!$request->has('new_password') || empty($request->has('new_password'))) {
            return new JsonResponse(array("status#" => "0" , "message#" => "Invalid new password!"), 200);
        }

        $result = DB::table('tbl_members')
                    ->select('password')
                    ->where('id', '=', $user_id)
                    ->first();

        if(!$result || $result['password'] != $request->input('old_password')) {
            return new JsonResponse(array("status#" => "0" , "message#" => "Old password does not match!"), 200);
        }

        $data['password'] = $request->input('new_password');

        if($data) {
            DB::table('tbl_members')
                ->where('id', $user_id)
                ->update($data);
        }

        return new JsonResponse(array("status#" => "1" , "message#" => "Password updated successfully!"), 200);
    }

	
    /**
     * Update user's information.
     * @param  \Illuminate\Http\Request     $request
     * @return \Illuminate\Http\Response
     */
    public function updateProfile_old(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" , "=" , $user_id)
                    ->update(["user_id" => 0]);
               /*  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#" => "1" , "message#" => "Successfully logout") , 200);
                // doen by tarun on 2-june-2017 as ppl were facing issue when tryiong to logout
				//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
        ));
    }

	// 	Following function will receive follwoing parameters
	//  ----------------------------------------------------
	//	type: Free Trial / Paid / Renew
	// 	memid (if user is not logged in) / token (if user is logged in)
	//	price
	//	currency: INR / USD
	//	product
    public function UpdateUserPlanBeforePayemt(Request $request)
    {
        if($request->has('plancode'))
        {
			 /*if($request->has('type'))
				$type = $request->input('type');	
			if($request->has('member_id'))
				$member_id = $request->input('member_id');	
			if($request->has('token'))
				$token = $request->input('token');	
			if($request->has('currency'))
				$currency = $request->input('currency');	
			if($request->has('price'))
				$price = $request->input('price');	
			
			if( $type == 'Free Trial' ){
				$start_date= date("Y-m-d");
				$end_date=date("Y-m-d",strtotime("$start_date +14 days"));
				$arr['tbl_reg_logs']=array(
					'memid'=>$member_id,
					'startdate'=>$start_date,
					'enddate'=>$end_date,
					'f_time'=>$GLOBALS['currTime'],
					'f_product'=>'MA',
					'f_tenure'=>'Free Trial',
					'status'=>$status,
					'selected_products'=>"Mobile App",
					'comments'=>"from mobile app",
					'created_on'=>date("Y-m-d H:i:s")
				);				
				 $r = create_logs_from_array_of_array($arr);
				 
				 if($request->has('plancode') == 'ios')
				    return "Free Trial:" . 1;				 
				 else
				    echo "android";
			} elseif( $type == 'Paid' ){
			    if($request->has('plancode') == 'ios'){
			        $received_thru = "ios";
			        $order_id = '';
			    } else {
    				$order_id = getSMorderNoForCCAVENUE("SM");
    
    				include_once("/home/steelmin/public_html/sm_group_events/regProcess/paypal_country.php");
    				$ip_countryName = qryToCommaSepString("
    					select country 
    					from tbl_country 
    					where id in ( 
    						select country 
    						from tbl_members 
    						where id=$member_id
    					)
    				"
    				);
    				
    				if( $currency == "USD"){
    					if(in_array(strtoupper($ip_countryName), $_paypal_country)){
    						$pymtURLToredirectTo =  "https://www.steelmint.com/paypal/payment.php";
    						$received_thru = "Paypal";
    					} else {
    						$pymtURLToredirectTo =  "https://www.steelmint.com/pay/newCheckOut.php";
    						$received_thru = "CCAvenue - International";
    					}	
    				} else {
    					$received_thru = "CCAvenue - Domestic";
    					$pymtURLToredirectTo = "https://www.steelmint.com/pay/newCheckOut.php";
    				}				        
			    }

				$start_date= date("Y-m-d");
				$end_date=date("Y-m-d",strtotime("$start_date +365 days"));
				$arr['tbl_reg_logs']=array(
					'memid'=>$member_id,
					'startdate'=>$start_date,
					'enddate'=>$end_date,
					'f_time'=>$GLOBALS['currTime'],
					'f_product'=>'MA',
					'f_tenure'=>'One Year',
					'status'=>'Pending',
					'selected_products'=>"Mobile App",
					'comments'=>"from mobile app",
					'amtPaid'=>$price,
					'created_on'=>date("Y-m-d H:i:s"),
					'received_thru' => $received_thru,
					'billNo' => $order_id,
					'card_category' => $currency
				);
				$r = create_logs_from_array_of_array($arr);
				$_log_id = $r['tbl_reg_logs'];
				
				 if($request->has('plancode') == 'ios'){
				    return "Paid:" . $_log_id;     
				 } else {
    				if( $pymtURLToredirectTo ==  "https://www.steelmint.com/pay/newCheckOut.php" )
    					header($pymtURLToredirectTo . "?uid=$member_id&pymtSrc=MOB_APP&productPurchased=MOB_APP&amt=$price&currency=$currency&orderid=$order_id");
    				else
    					header($pymtURLToredirectTo . "?reglogs_id=$_log_id&uid=".$member_id."&pymtSrc=MOB_APP&item_desc=Payment for Order :".$order_id."&amt=".$price."&output=embed");
				 }
			} elseif( $type == 'Renew' ){
				if($request->has('token'))
				{
					$token = $request->input('token');
					$auth = new authentication();

					$member_id = $auth->authToken($token);
					if(!$member_id)
						abort(403, "Unauthorized action. Token access denied") ;
					else{
						return "Renew:" . 1234;
					}
				} else
					abort(403, "Unauthorized action. Token access denied") ;
			} */
			
             $user_id = null ;
            $email = null ;
            $city = '' ;
            $state = '';
			
            // 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,
				'lead_type'=>'A1'
                );

            }
            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='MA';

            $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') || $request->has('memid'))
			$type = $request->input('type');
		
		$data = array();
		
		
		/* $country = array('Asia & Asia-Pacific'=>array('India','China','Japan, Korea','Pakistan, Bangladesh, Nepal','Australia'),'South East Asia','Middle East & Africa','CIS Nations','Europe', 'America'=>array('US/Canada', 'Brazil'), 'Global');
		$category = array('Iron Ore','Coal','Ferrous Scrap','Ship Breaking','Semi Finish','Finish Long','Finish Flat','Ferro Alloy');
		$news_category = array('13,14,15'=>'Iron Ore',112=>'Coal',113=>'Ferrous Scrap',114=>'Ship Breaking',18=>'Semi Finish',19=>'Finish Long',22=>'Finish Flat',23=>'Ferro Alloy');  */
		$country = array(
            'Asia & Asia Pacific'    =>  array(
                'India',
                'China',
                'Japan, Korea',
                'Pakistan, Bangladesh, Nepal',
                'Australia'
            ),
            'South East Asia',
            'Middle East Africa',
            'CIS Nations',          
            'Europe',
            'America'   =>  array(
                'US/Canada',
                'Brazil'
            ),
            'Global'
        );

		$category = array('Iron Ore','Coal','Ferrous Scrap','Ship Breaking','Semi Finish','Finish Long','Finish Flat','Ferro Alloy');
		
        $news_category = array(
            '13,14,15'                  => 'Iron Ore',
            '16'                        => 'Coal',
            '17'                        => 'Ferrous Scrap',
            '114'                         => 'Ship Breaking',
            '18,19,20,21'               => 'Semi Finish',
            '4,25,26,2427'              => 'Finish Long',
            '24'                        => 'Finish Flat',
            '22,23,3659,3660,3661,3662' => 'Ferro Alloy'
        );
		$lead_type = array('Buy','Sell','Services');
		$pb_lead_type = array('Buy','Sell');
		
		// Modified by Mahip Kaushal on 30 Aug 2017 at 16:46
        // Reason: Portfolio query not needed for Price because it is already being handled by new prices function
        if($type == 'prices') {
            $data['prices']['cnf'] = array();
            $data['prices']['fob'] = array();
            $data['prices']['f'] = array();
        } else {
            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; */
					$category_id_arr = explode(",", $_category_id);

                    $categoryFlag=0;

                    if(isset($category_id_arr[0])) {
    					if(in_array($category_id_arr[0], $data['news']['category']))
    						$categoryFlag=1;
                    }
					
						$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; */
								$country_arr = explode(",", $_country_1);

								$countryFlag=0;

								if(isset($country_arr[0])) {
									if(in_array($country_arr[0], $data['news']['country']))
										$countryFlag=1;
								}
								$res['news']['country'][] = array(
														'name'=>$_country_1,
														'flag'=>$countryFlag,
														'parent'=>'N'
													);
							}
						}else{
							/* if(in_array($_country, $data['news']['country']))
								$countryFlag=1;
							else
								$countryFlag=0; */
							$country_arr = explode(",", $_country);

							$countryFlag=0;

							if(isset($country_arr[0])) {
								if(in_array($country_arr[0], $data['news']['country']))
									$countryFlag=1;
							}
							
							$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; */
					$category_id_arr = explode(",", $_category);

                    $categoryFlag=0;

                    if(isset($category_id_arr[0])) {
                        if(in_array($category_id_arr[0], $data['tenders']['category']))
                            $categoryFlag=1;
                    }
						$res['tenders']['category'][] = array(
												'name'=>$_category,
												'flag'=>$categoryFlag,
												'parent'=>''
											);
				}
				
				
				foreach( $lead_type as $_type){
						if(in_array($_type, $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($_type, $data['plantbee']['lead_type']))
							 $typeFlag=1;
						else
							$typeFlag=0;
						$res['plantbee']['lead_type'][] = array(
												'name'=>$_type,
												'flag'=>$typeFlag
											);
				}
				
			break;
			case "prices" :
                $filter = array();

                if($request->has('sterm')){
                    $sterm = $request->input('sterm');
                    $sterm = htmlspecialchars($sterm, ENT_QUOTES);
                    $filter['sterm'] = $sterm;
                }
                $filter['src'] = "APP";
				
                include($_ENV['COMMON_ROOT_PATH'].'/mappNew.php');

                $res = getPricesForApp($user_id, $filter);
				
			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($_type, $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_input = $request->input('rows');
                file_put_contents(storage_path() . "/errors/error-" . date('Y-m-d_H-i-s') . '.txt', $request->input('rows'));
                if($request->has('token'))
                    $rows = json_decode(stripcslashes($rows_input), true);
                else
                    $rows = $rows_input;
                    /* return new JsonResponse(array(
                "status#" => "1",
                "message#" =>$rows
            ));   */

                if($request->input('token') == 't8HzwKGvqMkztd2EVhfB9fOzvxQxGble') {
                    file_put_contents(storage_path() . "/test/test-" . date('Y-m-d_H-i-s') . '.txt', json_encode($request->all(), JSON_PRETTY_PRINT));
                    /*return new JsonResponse(array(
                        "status#" => "200" ,
                        "rows#" => $request->all()
                    ));*/
                }

                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 ) ;
        }
	}
}
