<?php
/**
 * Created by PhpStorm.
 * User: varun_2
 * Date: 19-12-2015
 * Time: 17:54
 */

namespace App\Http\Controllers;
use App\Http\Controllers\Action\ccavenueValidator;
use App\Http\Controllers\Action\Common;
use App\Http\Controllers\Action\Payment ;
use App\Http\Controllers\Action\PaypalValidator;
use App\Http\Controllers\Auth\authentication;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

use DB ;


class EventsController extends Controller
{

    /**
     * @var array
     * Array used to store designation with its number to correlate in delegate form
     */
    private $G_designation = array('1'=>'Director',
    '9'=>'Executive',
    '2'=>'Manager'
    );

    /**
     * @var array
     * Array used to store profile with its id to correlate in delegate form
     */
    private $G_profile = array('35'=>'Broker',
    '35'=>'Trader',
    '36'=>'Exporter',
    '36'=>'Importer',
    '34'=>'Manufacture');

    /**
     * @param Request $request
     * @return JsonResponse
     * Function to get all events data, in which we call other function in sm_events.php file
     */
    public function getallEvents(Request $request)
    {
        require ($_ENV['COMMON_ROOT_PATH'].'/sm_events.php');
        $user_id = '' ;
        if ($request->has('token')) {
            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);
        }
		
		$_res = getEvents('All',$user_id);

//        $rs = array() ;
//
//        for($i = 0 ; $i <  count($_res) ; $i++  )
//        {
//            $temp['id'] = $_res['event_id'] ;
//            $temp['name'] =  $_res[''] ;
//            $temp['date'] =  $_res['event_date'] ;
//            $temp['timestamp'] =  strtotime($_res['event_date'] );
//            $temp['end_timestamp'] =  $_res[''] ;
//            $temp['country'] =  $_res['event_venue'] ;
//            $temp['region'] =  $_res['event_location'] ;
//            $temp[''] =  $_res[''] ;
//            $temp[''] =  $_res[''] ;
//            $temp[''] =  $_res[''] ;
//            $temp[''] =  $_res[''] ;
//            $temp[''] =  $_res[''] ;
//            $temp[''] =  $_res[''] ;
//        }


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


    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * Get event data by its id having speakers, schedule, participants, sponsors and exhibitors
     */
   public function eventByID(Request $request, $id)
    {
        require ($_ENV['COMMON_ROOT_PATH'].'/sm_events.php');
        $all = array() ;

	$user_id = '' ;
        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');
        } 
		$all["id"] = strval($id) ;
		
		$filter_type='';
		if ($request->has('filter_type')) {
			$filter_type  = $request->input('filter_type');
		}
		switch($filter_type){
			case 'speakers':
				$all["speakers"] =  getSpeakers($id) ;
			break;
			case 'schedule':
				$all["schedule"] = getSchedules($id) ;
			break;
			case 'participant':
				$all["participant"] = getParticipant($id) ;
			break;
			/* case 'sponsors':
				$all['sponsors'] = [] ;
				$all["exhibitors"] = [];
				$sponsers_exibitor = getSponsors($id ) ;
				$sponsers = $sponsers_exibitor['sponsors'] ;
				if(is_array($sponsers))
				{
					foreach( $sponsers  as $name=> $spon )
						$all['sponsors'][] = array(
							"name" => $name ,
							"value" => $spon
						);
				}
			break; */
			case 'exhibitors':
				$all["exhibitors"] = [];
				$sponsers_exibitor = getSponsors($id ) ;
				$all["exhibitors"] = $sponsers_exibitor['exhibitors'] ;
			break;
			case 'accommodations':
			case 'accomodations':
				$all["accommodations"] = [];
				$res = getAccommodations($id ) ;
				$all["accommodations"] = $res['accommodations'] ;
			break;
			case 'sponsors_exhibitors':
			case 'sponsors':
				$all['sponsors'] = [] ;
				$all["exhibitors"] = [];
				$sponsers_exibitor = getSponsors($id ) ;
				$sponsers = $sponsers_exibitor['sponsors'] ;
				if(is_array($sponsers))
				{
					foreach( $sponsers  as $name=> $spon )
						$all['sponsors'][] = array(
							"name" => $name ,
							"value" => $spon
						);
				}
				  
				$all["exhibitors"] = $sponsers_exibitor['exhibitors'] ;
			break;
			case 'all':
					  
				$all["user_details"] = getEvents($type='All', $user_id, $event_id=$id);
			break;
			default:
				$all["speakers"] =  getSpeakers($id) ;
				$all["schedule"] = getSchedules($id) ;
				$all["participant"] = getParticipant($id) ;
				$all['sponsors'] = [] ;
				$all["exhibitors"] = [];
				$sponsers_exibitor = getSponsors($id ) ;
				$sponsers = $sponsers_exibitor['sponsors'] ;
				if(is_array($sponsers))
				{
					foreach( $sponsers  as $name=> $spon )
						$all['sponsors'][] = array(
							"name" => $name ,
							"value" => $spon
						);
				}
				  
				$all["exhibitors"] = $sponsers_exibitor['exhibitors'] ;
				
				$all["accommodations"] = [];
				$res = getAccommodations($id ) ;
				$all["accommodations"] = $res['accommodations'] ;
			break;
		}		    

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

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * Function to get participants filter list according to event id
     */
    public function getFilters(Request $request, $id )
    {

        require ($_ENV['COMMON_ROOT_PATH'].'/sm_events.php');

        $country_filter = array();

        $temp = getParticipantFilters($id) ;

        $filter = array(
           /*  [
                "filter" => "designation" ,
                "sub_filter" => $temp['designation'] ,
            ], */
            [
                "filter" => "profile" ,
                "sub_filter" => $temp['profile'] ,
            ],
            [
                "filter" => "company" ,
                "sub_filter" => $temp['company'] ,
            ],
            [
                "filter" => "country" ,
                "sub_filter" => $temp['country'] ,
            ]
        );

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

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * Function to get participants list and you can also apply filter to it.
     */
    public function getparticipants(Request $request, $id)
    {
        $all = array() ;

//print_r ($request->input('filters'));
        require ($_ENV['COMMON_ROOT_PATH'].'/sm_events.php');
        if($request->has('filters'))
        {
            $filter = array() ;
            //designation
           /*  if(!empty($request->input('filters')['designation']))
            {
                $filter['designation'] = explode  ( ";" , $request->input('filters')['designation'] ) ;
                for($i = 0 ; $i < count($filter['designation']) ; $i++ )
                    $filter['designation'][$i] = array_search( $filter['designation'][$i] , $this->G_designation ) ;
                $filter['designation'] = implode( "," ,$filter['designation'] ) ;

            } */

            //profile
            if(!empty($request->input('filters')['profile']))
            {
                /* $filter['profile'] = explode  ( ";" , $request->input('filters')['profile'] ) ;
                for($i = 0 ; $i < count($filter['profile']) ; $i++ )
                    $filter['profile'][$i] = array_search( $filter['profile'][$i] , $this->G_profile );
                $filter['profile'] = implode( "," ,$filter['profile'] ) ; */
				$filter['profile'] = str_replace( ";" ,",", $request->input('filters')['profile'] ) ;
            }

            //company
            if(!empty($request->input('filters')['company']))
                $filter['company'] = str_replace  ( ";" , "," , $request->input('filters')['company'] ) ;

            //country
            $filter['country'] = null ;
            if(!empty($request->input('filters')['country']))
            {
                $filter['country'] = explode  ( ";" , $request->input('filters')['country'] ) ;
                $temp = DB::table('tbl_country')
                    ->select('id')
                    ->whereIn( 'country' , $filter['country'])
                    ->get() ;
                $filter['country'] = null ;
                for($i = 0 ; $i < count($temp) ; $i++ )
                {
                    $filter['country'] [] = $temp[$i]['id'] ;
                }
                $filter['country'] = implode( "," ,  $filter['country'] ) ;
            }
//var_dump($filter) ;
            $all["participant"] = getParticipant($id ,$filter ) ;
            return new JsonResponse( array( "status#" => "1" , "data#" => $all ) );
        }
        else
            $all["participant"] = getParticipant($id ) ;

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

    }
	
	 /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * Function to get accomodation list.
     */
    public function getAccomodations(Request $request, $id)
    {
        $all = array() ;

//print_r ($request->input('filters'));
        require ($_ENV['COMMON_ROOT_PATH'].'/sm_events.php');
        
		$accomodations = getAccommodations($id) ;

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

    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * Get events package details with tax, and currently is not used
     */
    public function getEventPackage(Request $request, $id)
    {
        require ($_ENV['COMMON_ROOT_PATH'].'/sm_events.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']));
        }
			
		if( $id == 15 ){
			$dt=json_decode(@file_get_contents('https://freegeoip.net/json/'.$ipAddress));
			if ($dt!=null) $ip_countryName= strtoupper($dt->country_name);
			
			
			if( 'INDIA' == $ip_countryName )
				$_rs_array = array("plans"=> array("early_bird"=> array("is_active"=> 1,"onspot_date"=> "2018-03-11","p_type"=> "INR","tab_name"=> "With Accommodation","delegate"=> array("Price"=> "76000-1")),"standard"=> array("is_active"=> 1,"standard_date"=> "16 May 2018","p_type"=> "INR","tab_name"=> "Without Accommodation","delegate"=> array("Price"=> "57000-1"))),"note"=> "GST @18% applicable for Indian Clients; 1USD=INR65.1 conversion for Indian clients","delegate_note"=> "For more details ","is_tax_applicable"=> " + GST 18%");	
			else
				$_rs_array = array("plans"=> array("early_bird"=> array("is_active"=> 1,"onspot_date"=> "2018-03-11","p_type"=> "INR","tab_name"=> "With Accommodation","delegate"=> array("Price"=> "1199-1")),"standard"=> array("is_active"=> 1,"standard_date"=> "16 May 2018","p_type"=> "INR","tab_name"=> "Without Accommodation","delegate"=> array("Price"=> "899-1"))),"note"=> "GST @18% applicable for Indian Clients; 1USD=INR65.1 conversion for Indian clients","delegate_note"=> "For more details ","is_tax_applicable"=> " + GST 18%");	
		} else {        
			$_rs_array = getEventPackageDetail($ipAddress , $id ) ;
		}

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

    public function getPriceDetail(Request $request, $id)
    {
        $user_id = '' ;
        if ($request->has('token')) {
            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);
        }

        if($request->has('delegate_number')
        && $request->has('type')
        )
        {
            require ($_ENV['COMMON_ROOT_PATH'].'/sm_events.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']));
            }
			
			$res = getPaymentDetails ($ipAddress , $user_id , $id , $request->input('delegate_number') ,  $request->input('type') ) ;
			
            return new JsonResponse(array(
                "status#" => "1" ,
                "data#" => $res
            )) ;
        }
        else{
             return new JsonResponse(array(
                "status#" => "206" ,
                "data#" => 'Partial input'
            )) ;
			//abort(206, 'Partial input') ;
		}
    }

    public function delegateSubmitForm(Request $request , $id )
    {
         ///$req = $request->json()->all() ;
		$req['delegates'] = $request->input('delegates');
        $req['type'] = $request->input('type');
        $req['token'] = $request->input('token');
        $req['subTotal'] = $request->input('subTotal');
        $req['discount'] = $request->input('discount');
        $req['SBCess'] = $request->input('SBCess');
        $req['serviceTax'] = $request->input('serviceTax');
        $req['amtToCharge'] = $request->input('total');
		
		/* echo $req['type'] . " -- " . $req['token'] . " -- " .$req['subTotal'] . " -- " .$req['discount'] . " -- " .$req['SBCess'] . " -- ".$req['amtToCharge'] . " -- " ; */
		if( !empty($req['type']) && !empty($req['delegates']))
        {

            $delegate_number = count($req['delegates']) ;
            /**
             * For IpAddress
             */
            $ipAddress = $_SERVER['REMOTE_ADDR'];
            if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
                $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
            }
            $user_id = '' ;
            if(!empty($req['token']))
            {
                $token = $req['token'];
                $auth = new authentication();
                $user_id = $auth->authToken($token);
            }

            require ($_ENV['COMMON_ROOT_PATH'].'/sm_events.php');

//            $ipAddress = "8.8.4.4" ;
//            echo "proceed after" ;
            //$response =  prceedWithDelegatesDetails($ipAddress , $id , $user_id , $req , $delegate_number , $req['type']) ;
			if(intval($req['subTotal'])<1)
				$req['subTotal'] = $req['amtToCharge'];
            $response =  prceedWithDelegatesDetails($ipAddress , $id , $user_id , $req , $delegate_number , $req['type'], $visited_on="MOBAPP", $selected_ids='', $subTotal=$req['subTotal'], $discount=$req['discount'], $SBCess=$req['SBCess'], $serviceTax=$req['serviceTax'], $amtToCharge=$req['amtToCharge']) ;
			 
			if($response == false){
                return new JsonResponse(array(
                    "status#" => "1110" ,
                    "message#" => "Error Please try again" ,
                )) ;
			}else{
				return array(
					"status#" => "1" ,
					"message#" => $response 
				);
			}
//            echo "after response" ;
            /* $pay = getPaymentDetails($ipAddress , $user_id , $id , $delegate_number ,  $req['type'] ) ;

            if($response == false)
                return new JsonResponse(array(
                    "status#" => "1110" ,
                    "message#" => "Error Please try again" ,
                )) ;

            $arrMiscDtls = array(
                'event_id' => $id ,
                'type' => $req['type'] ,
                '_no_delegates' => $delegate_number
            ) ;
            $currency = null ;
            $response['page'] = str_replace('https://events.steelmintgroup.com/checkout.php' , 'https://www.steelmint.com/api/public/v3/action/events/payment' , $response['page'] ) ;
            if($response['payment_gateway'] == 'CCAVENUE')
                $currency = 'INR' ;
            else
            {
                unset($response['page']) ;
                $currency = 'USD' ;
            }


//            var_dump($response) ;
            $payment = new Payment( $pay["delegates"]['Total'] , $currency , $response['payment_gateway'], 'event', $user_id, $arrMiscDtls ) ;
            $payment->log_payment_before( $response['bill_no'] , $response['log_id'] ) ;
            unset($response['log_id']) ;

            $response['payment_detail'] = $pay["delegates"] ;
//            $response['page'] = str_replace('https://events.steelmintgroup.com/checkout.php' , 'https://www.steelmint.com/api/public/v3/action/events/payment' , $response['page'] ) ;
            $response['currency'] = $currency ;


            return new JsonResponse(array(
                "status#" => "1" ,
                "data#" => $response ,
            )) ; */
        }
        else
             return new JsonResponse(array(
                    "status#" => "1234" ,
                    "message#" => "Outer Error Please try again" ,
                )) ;
    }

    public function delegateContactus(Request $request, $eventId)
    {
        if($request->has('name')
            && $request->has('email')
            && $request->has('phoneno')
            && $request->has('company')
            && $request->has('country_name')
        )
        {
            $user_id = '' ;
            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');
            }

            require ($_ENV['COMMON_ROOT_PATH'].'/sm_events.php');

            $input = array(
                "name" => $request->input('name'),
                "email" => $request->input('email'),
                "phoneno" => $request->input('phoneno'),
                "company" => $request->input('company'),
                "country" => $request->input('country_name')
            ) ;

            $res = contactUs($eventId, $user_id ,  $input ) ;

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

        }
        else
            abort(206, 'Partial input') ;
    }

    public function after_payment(Request $request )
    {
        $payment_gateway = null ;
        $amount = null ;
        $status = null ;
        $currency = null ;
        if($request->has('encResp'))
        {

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

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

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

//            var_dump(json_encode($res['info'])) ;

//            if(!empty($res['info']['order_id']))
//                DB::table('payment_log')
//                    ->where('order_id' , '=' , $res['info']['order_id'] )
//                    ->update(["payment_gateway_response" => $res['info']] ) ;

//            $byte_written = \File::put('ccavenue_receipt.txt', var_export($res, true ));

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

                if($res == true )
//                    return view('ccavenue', ['status' => "1" , "data" => "Payment successful"]);
                    return new JsonResponse(array(
                        "status#" => "1" ,
                        "message" => "Payment successful"
                    )) ;
                else
//                    return view('ccavenue', ['status' => "1" , "data" => $res['status'] ]);
                    return new JsonResponse(array(
                        "status#" => "1" ,
                        "message#" => $res['status']
                    )) ;
            }
            else
            {
//                DB::table('payment_log')
//                    ->update(["status" => "failed" , "payment_gateway_response" => json_encode($res['info'])] )
//                    ->where('order_id' , '=' , $res['info']['order_id'] )
//                    ->where('type', '=' , 'event') ;

                return new JsonResponse(array(
                    "status#" => "1012" ,
                    "message#" => "Payment status not completed"
                )) ;

//                return view('ccavenue', ['status' => "1012" , "data" => "Payment status not completed"]);
            }

        }
        else if($request->has('order_id')
            && $request->has('payment_gateway')
            && $request->has("token")
            && $request->has('sale_id')
        )
        {
            $user_id = '' ;
            if(!empty($req['token']))
            {
                $token = $req['token'];
                $auth = new authentication();
                $user_id = $auth->authToken($token);
            }
            $return = array() ;

            switch( strtoupper($request->input("payment_gateway") ) )
            {
                case 'PAYPAL':
                    $payment_gateway = "PAYPAL" ;
                    $paypal  = new PaypalValidator() ;
                    if($request->has('sale_id'))
                    {
                        $pay = $paypal->verifyPayment($request->input("sale_id")) ;
                        $data = $pay->toArray() ;

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

                        if($data['intent'] == 'sale' && $data['state'] == 'approved' && $data['intent'] == 'sale')
                        {
                            $amount = $data['transactions'][0]['amount']['total'] ;
                            $status = $data['state'] ; //created; approved; failed; canceled; expired; pending.
                            $currency = $data['transactions'][0]['amount']['currency'] ;
                        }
                        else
                            return (array(
                                "status#" => "1010",
                                "payment_status" => $pay['state']
                            )) ;

//                        $amount = $sale->getAmount()->getTotal();
//                        $status = $sale->getState() ; //Valid Values: ["completed", "partially_refunded", "pending", "refunded"]
//                        $currency = $sale->getAmount()->getCurrency();

//                        echo "Amount:".$amount."  Status:".$status."  Currency:".$currency ;
                    }
                    else
                        abort(206, "Enter with sale_id") ;
                    break;

                default:
                    return new JsonResponse(array(
                        "status#" => "1" ,
                        "data#" => "Error in payment redirection"
                    ));
                    break;
            }

            if($status == "approved")
            {
//                echo "amount: $amount\tcurrency: $currency" ;
                $payment = new Payment( $amount , $currency , $payment_gateway, 'event', $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#" => "1301" ,
                        "message#" => "Payment not updated"
                    ));
            }
            else
                return new JsonResponse(array(
                    "status#" => "1301" ,
                    "message#" => "Payment status not completed"
                ));

            return new JsonResponse(array(
                "status#" => "1" ,
                "data#" => $sale->toArray()
            ));
        }
        else
            abort(206, "Partial Input") ;
    }
	public function getEventContacts(Request $request)
    {
        $user_id = 0;
        $event_id = 0;
        $member_ids = array();
        $contacts = array();
 
	
        if($request->has('token')) {
            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);
            if(!$user_id) {
                return new JsonResponse(array("status#" => '1001', "message#" => "Unauthorized action. Token access denied"), 401);
            }
        } else {
            return new JsonResponse(array("status#" => '1002', "message#" => "Unauthorized action. Token access denied"), 400);
        }

        if($request->has('event_id')) {
            $event_id = $request->input('event_id');
        }

        if($event_id) {

            $sql = "SELECT m.`id`,  m.`job_title` as designation, m.`company` as company_name, m.`company_profile`, m.`country`";
            $sql .= ", CASE";
            $sql .= " WHEN m.billing_name = '' THEN m.name";
            $sql .= " ELSE m.billing_name";
            $sql .= " END as name";
            $sql .= ", CASE";
            $sql .= " WHEN m.`send_email_to` = 'R' THEN m.`email`";
            $sql .= " ELSE m.`addtnl_email`";
            $sql .= " END as email";
            $sql .= ", CASE";
            $sql .= " WHEN m.`send_email_to` = 'R' THEN m.`phoneno`";
            $sql .= " ELSE m.`alternate_mob_no`";
            $sql .= " END as phoneno";
            $sql .= ", c.`country` as location";
            $sql .= ", m.`isd_code` ";
            $sql .= ", (SELECT sm.`pRemarks` FROM `tbl_sm_events_QRcode_contacts` sm WHERE sm.memid = " . $user_id . " AND sm.`contact_id` = m.`id` AND sm.`event_id` = " . $event_id . " LIMIT 1) as remark";

            $sql .= " FROM `tbl_members` m";
            $sql .= " LEFT JOIN `tbl_state_city` sc ON(m.`country` = sc.`country_id` AND m.`state` = sc.`state_id` AND m.`city` = sc.`city_id`)";
            $sql .= " LEFT JOIN `tbl_country` c ON(m.`country` = c.`id`)";

            $sql .= " WHERE m.`id` IN (SELECT sm.`contact_id` FROM `tbl_sm_events_QRcode_contacts` sm WHERE sm.`memid` = " . $user_id . " AND sm.`event_id` = " . $event_id . ")";

            $sql .= " GROUP BY m.`id`";
            $sql .= " ORDER BY m.`id` DESC";

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

            $contacts = array();

            if($results) {
                foreach($results as $result) {

                    if(strlen($result['location']) <= 3) {
                        $location = strtoupper($result['location']);
                    } else {
                        $location = ucwords(strtolower($result['location']));
                    }
					if( $result['country'] == 113 || $result['country'] == 0 )
						$ph = "+91" . $result['phoneno'];
					else
						$ph = $result['isd_code'] . $result['phoneno'];
                    
					 $remarks = trim($result['remark']);
					if($this->isBase64Encoded($remarks)){
						$remarks = utf8_decode(base64_decode($remarks));
					}
						
					/* if ( base64_encode(base64_decode($remarks)) === ){
						$remarks =  base64_decode($remarks) . ' is valid :: '.$remarks;
					} else {
						$remarks .= base64_encode(base64_decode($remarks));
					} */
					
					$contacts[] = array(
                        'memid'             =>  $result['id'],
                        'name'              =>  $result['name'],
                        'company_name'      =>  $result['company_name'],
                        'company_profile'   =>  $result['company_profile'],
                        'location'          =>  $location,
                        'phoneno'           =>  $ph,
                        'email'             =>  $result['email'],
                        'eventid'           =>  $event_id,
                        'designation'       =>  $result['designation'],
                        'pRemarks'          =>  $remarks///base64_decode($remarks)
                        //'pRemarks'          =>  html_entity_decode($result['remark'] , ENT_QUOTES)
                    );
                }
            }

        }
if($request->has('debug')){
	echo $sql . "<pre>";
	print_r ($contacts);
	dd();
}
	
        return new JsonResponse(array(
            "status#"   => "1" ,
            "data#"     => $contacts
        ));

    }
	
	public function isBase64Encoded($str) 
	{
		try
		{
			$decoded = base64_decode($str, true);

			if(base64_encode(base64_decode($str, true)) === $data) {
				return true;
			}
			else {
				return false;
			}
		}
		catch(Exception $e)
		{
			// If exception is caught, then it is not a base64 encoded string
			return false;
		}

	}

	public function is_base64($s)
	{
		  return (bool) preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s);
	}
	
	function is_base64_encoded($data)
    {
        if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function storeEventContacts(Request $request)
    {
        $user_id = 0;
        $event_id = 0;
        $member_ids = '';
        $remark = '';
        $existingContactIds = array();
        $newContactIds = array();

        if($request->has('token')) {
            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);
            if(!$user_id) {
                return new JsonResponse(array("status#" => '1001', "message#" => "Unauthorized action. Token access denied"), 401);
            }
        } else {
            return new JsonResponse(array("status#" => '1002', "message#" => "Unauthorized action. Token access denied"), 400);
        }

        if($request->has('event_id') && !empty($request->input('event_id'))) {
            $event_id = $request->input('event_id');
        } else {
            return new JsonResponse(array("status#" => '1003', "message#" => "Event Id required!"), 400);
        }

        if($request->has('member_ids') && !empty($request->input('member_ids'))) {
            $member_ids = rtrim(preg_replace('/\s+/', '', $request->input('member_ids')), ",");
        } else {
            return new JsonResponse(array("status#" => '1004', "message#" => "Member_Id(s) required!"), 400);
        }

        if($request->has('pRemarks')) {
            $remarks = rtrim($request->input('pRemarks'));
        }

        if($member_ids) {
            $insertRows = array();
			
            $member_ids = explode(",", $member_ids);
            $remarks = explode("/*/", urldecode($remarks));
            $createdAt = date('Y-m-d H:i:s');

            $sql = "SELECT DISTINCT(`contact_id`) FROM `tbl_sm_events_QRcode_contacts` WHERE `memid` = " . $user_id . " AND `event_id` = " . $event_id . " AND `contact_id` IN (" . implode(",", $member_ids) . ")";

            $existingContactIdResult = DB::select($sql);
            if($existingContactIdResult) {
                foreach($existingContactIdResult as $existingContactId) {
                    $existingContactIds[] = $existingContactId['contact_id'];
                }
            }

            foreach($member_ids as $key => $member_id) {
                if(!in_array($member_id, $existingContactIds)) {
                    $remark = (isset($remarks[$key]) ? $remarks[$key] : '');
    				//$remark  = htmlentities($remark , ENT_QUOTES);
                    $insertRows[] = "('" . $user_id . "', '" . $event_id . "', '" . $member_id . "', '" . $remark . "', '" . $createdAt . "')";
                    $newContactIds[] = $member_id;
                }
            }

            if($insertRows) {
                $sql = "INSERT INTO `tbl_sm_events_QRcode_contacts` (`memid`, `event_id`, `contact_id`, `pRemarks`, `created_at`) VALUES ";
                $sql .= implode(", ", $insertRows);

                DB::insert($sql);
            }
        }

        return new JsonResponse(array(
            "status#"               => "1" ,
            "message#"              => "successfully saved",
            "existing_member_ids"   =>  implode(",", $existingContactIds),
            "new_member_id"         =>  implode(",", $newContactIds)
        ));
    }

    public function deleteEventContact(Request $request)
    {
        $user_id = 0;
        $event_id = 0;
        $member_id = 0;

        if($request->has('token')) {
            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);
            if(!$user_id) {
                return new JsonResponse(array("status#" => '1001', "message#" => "Unauthorized action. Token access denied"), 401);
            }
        } else {
            return new JsonResponse(array("status#" => '1002', "message#" => "Unauthorized action. Token access denied"), 400);
        }

        if(!$request->has('event_id')) {
            return new JsonResponse(array("status#" => '1003', "message#" => "Missing Event Id!"), 400);
        }

        if(!$request->has('member_id')) {
            return new JsonResponse(array("status#" => '1004', "message#" => "Missing Member Id!"), 400);
        }

        $event_id = $request->input('event_id');
        $member_id = $request->input('member_id');

        DB::table('tbl_sm_events_QRcode_contacts')
            ->where('memid', '=', $user_id)
            ->where('event_id', '=', $event_id)
            ->where('contact_id', '=', $member_id)
            ->delete();

        return new JsonResponse(array("status#" => '1', "message#" => "Contact deleted successfully!"), 200);
    }
	
	public function updateEventContactRemark(Request $request)
    {
        $user_id = 0;
        $event_id = 0;
        $member_id = 0;

        if($request->has('token')) {
            $token = $request->input('token');
            $auth = new authentication();
            $user_id = $auth->authToken($token);
            if(!$user_id) {
                return new JsonResponse(array("status#" => '1001', "message#" => "Unauthorized action. Token access denied"), 401);
            }
        } else {
            return new JsonResponse(array("status#" => '1002', "message#" => "Unauthorized action. Token access denied"), 400);
        }

        if(!$request->has('event_id')) {
            return new JsonResponse(array("status#" => '1003', "message#" => "Missing Event Id!"), 400);
        }

        if(!$request->has('member_id')) {
            return new JsonResponse(array("status#" => '1004', "message#" => "Missing Member Id!"), 400);
        }

        $event_id = $request->input('event_id');
        $member_id = $request->input('member_id');
        $remarks = $request->input('remark_value');
		//$remarks  = htmlentities($remarks , ENT_QUOTES);//html_entity_decode
		
		if($user_id!='' && $event_id!='' && $member_id!=''){
			DB::table('tbl_sm_events_QRcode_contacts')
                    ->where('memid', '=', $user_id)
					->where('event_id', '=', $event_id)
					->where('contact_id', '=', $member_id)
                    ->update(["pRemarks" => $remarks] ) ;
        }
		
        return new JsonResponse(array("status#" => '1', "message#" => "Notes updated successfully!"), 200);
    }

	public function storeEventRegistry(Request $request)
    {
        $member_ids = '';$event_ids ='';
        $dates = '';
        $existingContactIds = array();

        if($request->has('event_ids') && !empty($request->input('event_ids'))) {
						$event_ids = rtrim(preg_replace('/\s+/', '', $request->input('event_ids')), ",");
        } else {
            return new JsonResponse(array("status#" => '1003', "message#" => "Event Id(s) required!"), 400);
        }

        if($request->has('member_ids') && !empty($request->input('member_ids'))) {
            $member_ids = rtrim(preg_replace('/\s+/', '', $request->input('member_ids')), ",");
        } else {
            return new JsonResponse(array("status#" => '1004', "message#" => "Member_Id(s) required!"), 400);
        }

        if($request->has('dates')) {
            $dates = rtrim($request->input('dates'));
				}

            $insertRows = array();
			
            $member_ids = explode(",",$member_ids);
			$event_ids = explode(",",$event_ids);
			$date = explode(",",$dates);
            $createdAt = date("Y-m-d H:i:s", strtotime('+5 hours 30 minutes'));
			
						
						foreach($event_ids as $k=>$v){
							$insertRows[] = "('" . $v . "', '" . $member_ids[$k] . "', '" . $date[$k] . "', '" . $createdAt . "')";
					}
					if($insertRows) {
						$sql = "INSERT INTO `tbl_event_present` (`event_id`, `contact_id`, `app_sent_date`, `created_at`) VALUES ";
						$sql .= implode(", ", $insertRows);
						DB::insert($sql);
				  }


        return new JsonResponse(array(
            "status#"               => "1" ,
            "message#"              => "successfully saved"
        ));
    }
	
}
