<?php
namespace App\Http\Controllers\v2019;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Auth\authentication;
use App\Rules\Source;
use Session;
use Validator;

class Events1Controller extends Controller
{ 

		public function getAlerts(Request $request)
		{
			$memId = \App\Helper::getMemId();
				$data = json_decode($request->getContent(), true);
				$validator = Validator::make($data, [
						'section' => 'required',
						'memId' => 'int',
				]);
				if ($validator->fails()) {
						$messages = $validator->messages();
						return response()->json([
								'status' => [
										"code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
										'message' => $messages
								]
						]);
				}
				$alertIds = \App\Alert::select('item_id')
						->where('section', $data['section'])
						->where('memid', $memId)
						->where('status', 'active')
						->pluck('item_id');
				return response()->json([
						'status' => [
								"code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
								'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg,
								'data' => (!empty($alertIds) ? $alertIds : [])
						]
				]);
		}

		public function removeAlerts(Request $request)
    {
        $memId = \App\Helper::getMemId();
        $data = json_decode($request->getContent(), true);
        $validator = Validator::make($data, [
            'section' => 'required',
            'memId' => 'int',
            'itemId' => 'required'
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
        $r = \App\Alert::where('item_id', $data['itemId'])
            ->where('section', $data['section'])
            ->where('status', 'active')
            ->where('memid', $memId)
            ->first();
        if (!empty($r)) {
            \App\Alert::where('id', $r->id)
                ->update(['status' => 'inactive']);
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg
                ]
            ]);

        } else {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => "Record already deleted or no record found"
                ]
            ]);
        }
    }

    public function addAlerts(Request $request)
    {
        $memId = \App\Helper::getMemId();
        $data = json_decode($request->getContent(), true);
        $validator = Validator::make($data, [
            'section' => 'required',
            'itemId' => 'required',
            'memId' => 'int',
            'xDaysBefore' => 'int',
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }

        if (!isset($data['xDaysBefore'])) {
            $data['xDaysBefore'] = "";
        }
        if ($data['section'] == 'tender' && empty($data['xDaysBefore'])) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::InvalidInputsCode,
                    'message' => 'xDaysBefore only required for section tender'
                ]
            ]);

        } else if ($data['section'] != 'tender' && !empty($data['xDaysBefore'])) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::InvalidInputsCode,
                    'message' => 'xDaysBefore only required for section tender'
                ]
            ]);
        }
        $f = \App\Alert::where('item_id', $data['itemId'])
            ->where('section', $data['section'])
            ->where('memid', $memId)
            ->where('status', 'active')
            ->count();
        if ($f) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => 'Alert already exists'
                ]
            ]);
        }
        \App\Alert::insert([
            'memid' => $memId,
            'section' => $data['section'],
            'item_id' => $data['itemId'],
            'status' => 'active',
            'f_date' => date("Y-m-d"),
            'f_time' => date("h:i:s"),
            'x_days_before' => $data['xDaysBefore'],
        ]);
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => 'Successfully added to alert'
            ]
        ]);
		}
		

		public function getBookmark(Request $request)
    {
        $memId = \App\Helper::getMemId();
        $data = json_decode($request->getContent(), true);
        $validator = Validator::make($data, [
            'section' => 'required',
            'memId' => 'int',
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
        $bookmarkItemIds = \App\Bookmark::select('item_id')
            ->where('section', $data['section'])
            ->where('memid', $memId)
            ->where('status', 'active')
            ->pluck('item_id');
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg,
                'data' => (!empty($bookmarkItemIds) ? $bookmarkItemIds : [])
            ]
        ]);
    }

    public function removeBookmark(Request $request)
    {
        $memId = \App\Helper::getMemId();
        $data = json_decode($request->getContent(), true);
        $validator = Validator::make($data, [
            'memId' => 'int',
            'itemIds' => 'required',
            'source' => ['required', new Source],

        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
        $tblArray = \App\Helper::tblLists();

        try {
            if (array_key_exists($data['source'], $tblArray)) {
                $r = DB::table($tblArray[$data['source']])
                    ->where('id', $data['itemIds'])
                    ->where('status', 'active')
                    ->where('memid', $memId)
                    ->first();
                if (!empty($r)) {
                    \App\Bookmark::where('id', $r->id)
                        ->update(['status' => 'inactive']);
                    return response()->json([
                        'status' => [
                            "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                            'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg
                        ]
                    ]);
                } else {
                    return response()->json([
                        'status' => [
                            "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                            'message' => "Record already deleted or no record found"
                        ]
                    ]);
                }
            } else {
                return response()->json([
                    'status' => [
                        "code" => \App\RestApiResponseCodes::somethingWentWrongCode,
                        'message' => \App\RestApiResponseCodes::somethingWentWrongMsg,
                    ]
                ]);
            }
        } catch (\Exception $ex) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::somethingWentWrongCode,
                    'message' => \App\RestApiResponseCodes::somethingWentWrongMsg,
                ]
            ]);
        }

    }

    public function addBookmark(Request $request)
    {
        $memId = \App\Helper::getMemId();
        $data = json_decode($request->getContent(), true);
        $validator = Validator::make($data, [
            'section' => 'required',
            'itemIds' => 'required',
            'memId' => 'int',
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
        $f = \App\Bookmark::where('item_id', $data['itemIds'])
            ->where('section', $data['section'])
            ->where('memid', $memId)
            ->where('status', 'active')
            ->count();
        if ($f) {
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                    'message' => 'Bookmark already exists'
                ]
            ]);
        }
        \App\Bookmark::insert([
            'memid' => $memId,
            'section' => $data['section'],
            'item_id' => $data['itemIds'],
            'event_id' => (isset($data['eventID'])?$data['eventID']:''),
            'status' => 'active',
            'f_date' => date("Y-m-d"),
            'f_time' => date("h:i:s"),
        ]);
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => 'Successfully added to bookmarks'
            ]
        ]);
    }
		
    public function getEventListing(Request $request)
    {      
	   $result = array();
	   if($this->debug == TRUE){

	   } else {
		   //include_once "/home/steelmin/public_html/api/storage/v2019/event/events_list.php";
	   }
	   
	   $resourceType = "APP";		
	   if ($request->has('resourceType'))
		   $resourceType = strtolower($request->input('resourceType'));
	   
	   if($resourceType=='web'){
		   $code = 1001;
		   $message = "Success";
		   if ($request->has('memid') && $request->input('memid')!=''){
			   include_once "/home/steelmin/public_html/api/storage/v2019/web/web_events_list_post.php";
		   }else{
			   include_once "/home/steelmin/public_html/api/storage/v2019/web/web_events_list_post.php";
		   }
	   } else {
		$result = \apiQuery::getEventsRowSet();
		$code = 1001;
		$message = "Success";
	 }  
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}


	
    public function getEventSchedule(Request $request)
    {      
	   $result = array();
	   //include_once "/home/steelmin/public_html/api/storage/v2019/event/eventSchedule_list.php";
	   if ($request->has('eventId') && $request->input('eventId')!='')
		  $event_id = $request->input('eventId');
		else 
		  $event_id = '';

	   $result = \apiQuery::getSchedulesRowSet($event_id);
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }

    public function getEventSpeakerListing(Request $request)
    {      
	   $result = array();
	   //include_once "/home/steelmin/public_html/api/storage/v2019/event/eventSpeaker.php";
	   // if ($request->has('accessToken') && $request->input('accessToken')!='') {				
		 //$auth = new authentication();	
		//$token = $request->input('accessToken');
		//$user_id = true;
		if ($request->has('eventId') && $request->input('eventId')!='')
		  $event_id = $request->input('eventId');
		else 
		  $event_id = '';
		     
		//if ($user_id) {
		   $result = \apiQuery::getSpeakersRowSet($event_id);
		   $code = 1001;
		   $message = "Success";
	/*	}else{
			$code = 2013;
			$message = "Unauthorized action.";
		}
	  }else{
			///not loggedin/visitor///
			
			$code = 1001;
			$message = "Success";
		}*/
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }

	public function getEventSpeakerDetails(Request $request)
    {      
	   $result = array();
	   //include_once "/home/steelmin/public_html/api/storage/v2019/event/eventSpeaker.php";
	  // if ($request->has('accessToken') && $request->input('accessToken')!='') {				
		//$auth = new authentication();	
	//	$token = $request->input('accessToken');
	//	$user_id = true;
		if ($request->has('eventId') && $request->input('eventId')!='')
		  $event_id = $request->input('eventId');
		else 
		  $event_id = '';
		
		if ($request->has('speakerId') && $request->input('speakerId')!='')
		  $speaker_id = $request->input('speakerId');
		else 
		  $speaker_id = ''; 
		     
		//if ($user_id) {
		   $result = \apiQuery::getSpeakersRowSet($event_id,$speaker_id);
		   $code = 1001;
		   $message = "Success";
		/*}else{
			$code = 2013;
			$message = "Unauthorized action.";
		}
	  }else{
			///not loggedin/visitor///
			
			$code = 1001;
			$message = "Success";
		}*/
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }

    public function getEventAttendeeListing(Request $request)
    {      
	   $result = array();
	   //include_once "/home/steelmin/public_html/api/storage/v2019/event/attendees_list.php";
	  // if ($request->has('accessToken') && $request->input('accessToken')!='') {				
		//$auth = new authentication();	
	//	$token = $request->input('accessToken');
		//$user_id = true;

		  if ($request->has('event_id') && $request->input('eventId')!='')
		  $atnd_id = $request->input('eventId');
		else 
		  $atnd_id = '';  
		     
	//	if ($user_id) {
		   $result = \apiQuery::getParticipantRowSet($atnd_id);
		   $code = 1001;
		   $message = "Success";
	/*	}else{
			$code = 2013;
			$message = "Unauthorized action.";
		}
	  }else{
			///not loggedin/visitor///
			$code = 1001;
			$message = "Success";
		}*/
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }

    public function getEventSponsor(Request $request)
    {      
	   $result = array();
	   //include_once "/home/steelmin/public_html/api/storage/v2019/event/sponsor_list.php";
	   //if ($request->has('accessToken') && $request->input('accessToken')!='') {				
		//$auth = new authentication();	
		//$token = $request->input('accessToken');
	///	$user_id = true;
		if ($request->has('eventId') && $request->input('eventId')!='')
		  $event_id = $request->input('eventId');
		else 
		  $event_id = '';
		     
		//if ($user_id) {
		   $result = \apiQuery::getSponsorOrExibRowSet($event_id);
		   $code = 1001;
		   $message = "Success";
	/*	}else{
			$code = 2013;
			$message = "Unauthorized action.";
		}
	  }else{
			///not loggedin/visitor///
			$code = 1001;
			$message = "Success";
		}*/
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result["sponsors"]));
    }

    public function getEventExhibitor(Request $request)
    {      
	   $result = array();
	   //include_once "/home/steelmin/public_html/api/storage/v2019/event/exhibitor_list.php";
	   //if ($request->has('accessToken') && $request->input('accessToken')!='') {				
		//$auth = new authentication();	
		//$token = $request->input('accessToken');
		//$user_id = true;
		if ($request->has('eventId') && $request->input('eventId')!='')
		  $event_id = $request->input('eventId');
		else 
		  $event_id = '';
		     
		//if ($user_id) {
		   $result = \apiQuery::getSponsorOrExibRowSet($event_id);
		   $code = 1001;
		   $message = "Success";
		/*}else{
			$code = 2013;
			$message = "Unauthorized action.";
		}
	  }else{
			///not loggedin/visitor///
			
			$code = 1001;
			$message = "Success";
		}*/
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result["exhibitors"]));
    }

     public function getEventBookmark(Request $request)
    {      
	   $result = array();
	   include_once "/home/steelmin/public_html/api/storage/v2019/event/get_bookmarked.php";
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
           // $auth = new authentication();
           $token = $request->input('accessToken');
           if(empty($token)){
				///not loggedin/visitor///
				$code = 2013;
				$message = "User not found.";
			}else{
				///full data///
				$code = 1001;
				$message = "Success";
			}
        }else{
			///not loggedin/visitor///
			
			$code = 1001;
			$message = "Success";
		}
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }

    public function getEventAccommodation(Request $request)
    {      
	   $result = array();
	   //include_once "/home/steelmin/public_html/api/storage/v2019/event/accommodation_list.php";
	 //  if ($request->has('accessToken') && $request->input('accessToken')!='') {				
		//$auth = new authentication();	
		//$token = $request->input('accessToken');
		//$user_id = true;
		if ($request->has('eventId') && $request->input('eventId')!='')
		  $event_id = $request->input('eventId');
		else 
		  $event_id = '';
		  
		//if ($user_id) {
				$result = \apiQuery::getAccomodationRowSet($event_id);
				$code = 1001;
			  $message = "Success";
		//}else{
		//	$code = 2013;
		//	$message = "Unauthorized action.";
		//}
	 // }
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }

    public function getEventQRdetails(Request $request)
    {      
	   $result = array();
	   include_once "/home/steelmin/public_html/api/storage/v2019/event/get_QR_code_details.php";
		if ($request->has('accessToken') && $request->input('accessToken')!=''){
      ///$auth = new authentication();
			$token = $request->input('accessToken');
			$user = true;
		   if ($user) {
		    $result = \apiQuery::getQrDetails($user);
		   } else {
			$code = 2013;
			$message = "Unauthorized action.";
		   }
           
        } else {
			 $result = \apiQuery::getQrDetails('',$qiid);
			 $code = 1001;
			 $message = "Success";
		}
	     return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
		}
		
    public function saveScannedContact(Request $request)
    {      
	   $result = array();
		 include_once "/home/steelmin/public_html/api/storage/v2019/event/save_scanned_contact.php";
		 $data = base64_decode($request->input("qrCodeData"));
		 //$data = stripslashes($request->input('qrCodeData'));
		 $json = json_decode($data,true);
		 $token = $json["token"];
		 $event_id = $json["event_id"];
     $qr = $json["qr"];
		 foreach($qr as $k=>$v){
			 if(\apiQuery::saveQrDetails(1,25,$v))
			  $result[] = $v;
		 }
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $data));
    }

    public function getScannedContacts(Request $request)
    {      
	   $result = array();
	   include_once "/home/steelmin/public_html/api/storage/v2019/event/get_scanned_contacts.php";
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
           // $auth = new authentication();
           $token = $request->input('accessToken');
           if(empty($token)){
				///not loggedin/visitor///
				$code = 2013;
				$message = "User not found.";
			}else{
				///full data///
				$code = 1001;
				$message = "Success";
			}
        }else{
			///not loggedin/visitor///
			
			$code = 1001;
			$message = "Success";
		}
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	public function getEventsCount(Request $request){
		$result = array();
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			include_once "/home/steelmin/public_html/api/storage/v2019/web/web_report_count_post.php";
		} elseif($resourceType=='app') {
			///
		}else{
			$code = 2001;
			$message = "invalid input";
		}
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}

	public function genQR(){
		$codeContents = '[{"memid": "83757","eventid": "20","name": "MR. DIPEN SINGH GAUTAM","email": "DS.gautam@gmail.com","phoneno": "9806139099","company_name": "Gautam Services"}]';
		$arr = \apiQuery::qrGen($codeContents);
		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $arr));
	}

}    
    
?>