<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Customer extends CI_Controller
{

	function __construct()
	{
		parent::__construct();
		// $this->load->database();
		$this->load->model('customer_model');
		$this->load->model('common');
		$this->load->helper(array('form', 'url', 'string'));
		$this->load->library('form_validation');
		$this->load->library('session');
		define( 'API_ACCESS_KEY1', 'AAAAIpWpd14:APA91bGWyzOEV8wFb5j4gmvNsessh_Ce4BFvxt41dG8n1I3EuCv5i60YT3E-eY6HiRsjshjmyn5v5EX4uwF9UNnVRyRp1q2RHRBRxsZ0ye3BhfVUuof5b_50SoFI_SX1GsEwRrFRZ26k');
	}


	public function index()
	{

		$data['customerlist'] = array();
		//$this->customer_model->getall_customer();
		// var_dump($data['customerlist']);die;
		// $data['customerlist'] = [];
		
		$this->template->template_render('customer_management', $data);
	}

	public function appSettings()
	{

		$this->template->template_render('app_settings');
	}

	
	public function addinvitation()
	{
		$data['teams'] = $this->common->readdatafromcollectionwhereclause('Teams');
		$this->template->template_render('addinvitation',$data);
	}
public function addinvition(){
	$data=$this->input->post();
	$type=$this->input->post('type');

	$usercount = $this->common->readnumberofdocumentsincollectionbetween('Users', 'email', '=', $data['email']);
	if($usercount>0){

		$this->session->set_flashdata('warningmessage', 'User Has Been Already Exists');
		if($type =="user"){
			redirect(base_url().'customer/addinvitation');
		}else{
			redirect(base_url().'customer/addcoach');
		}
		
	}
	$id=time().rand();
	$data['id']=$id;
	$this->common->adddatamodel("Invitation", $data["id"], $data);
	$this->sendemailforinvation($data['email']);
		$this->session->set_flashdata('successmessage', ' Invitation has been sent successfully');
		if($type =="user"){
			redirect(base_url().'customer/addinvitation');
		}else{
			redirect(base_url().'customer/addcoach');
		}
		

}

function sendemailforinvation($email="adarvaish0@gmail.com"){
    
	$config['protocol'] = 'smtp';
	$config['smtp_host'] = 'ssl://mail.buzzwaretech.com';
	$config['smtp_port'] = '465';
	$config['smtp_user'] ='genral@buzzwaretech.com';
	$config['smtp_pass'] = 'ebmacs12341@#$';  //sender's password
	$config['mailtype']    = 'html';
	$config['charset']     = 'utf-8';
	$config['newline']     = "\r\n";
	$config['wordwrap']    = TRUE;
	
	$this->load->library('email', $config);
	$this->email->initialize($config);
	
	 $to_email = $email;
	//  $to_email = "aonraza399@gmail.com";
	 $from_email = "genral@buzzwaretech.com";
	 $message = "
	 <html>
	 <head>
		 <title>You're Invited! Athletes Edge</title>
	 </head>
	 <body>
		 <h1>Welcome to Athletes Edge!</h1>
		 <p>We're excited to invite you to try our new app. Click the link below to get started:</p>
		 <p><a href='https://yourappurl.com/register'>Join Now</a></p>
		 <p>Thank you for joining us!</p>
		 <p>Best regards,<br>Athletes Edge Team</p>
	 </body>
	 </html>
 ";
	


	 $this->email->from($from_email,'Athletes Edge'); 
	 $this->email->to($to_email);
	 $this->email->subject('App Invitation'); 
	 $this->email->message($message); 
			  if($this->email->send()){
					  $response['sucess']=1;
	$response['msg']="Email has been Send";
// 	echo json_encode($response);    
// exit;
			  }else{
		$response['sucess']=1;
	$response['msg']="Email not Send";
	 //echo json_encode($response);
	// echo 'Failed to send invitation email. Error: ' . $this->email->print_debugger();    
//exit;       
			  }

}

function sendemailforinvationexitinguser($email="adarvaish0@gmail.com",$name,$group){
    
	$config['protocol'] = 'smtp';
	$config['smtp_host'] = 'ssl://mail.buzzwaretech.com';
	$config['smtp_port'] = '465';
	$config['smtp_user'] ='genral@buzzwaretech.com';
	$config['smtp_pass'] = 'ebmacs12341@#$';  //sender's password
	$config['mailtype']    = 'html';
	$config['charset']     = 'utf-8';
	$config['newline']     = "\r\n";
	$config['wordwrap']    = TRUE;
	
	$this->load->library('email', $config);
	$this->email->initialize($config);
	
	 $to_email = $email;
	//  $to_email = "aonraza399@gmail.com";
	 $from_email = "genral@buzzwaretech.com";
	 $message = "
	 <html>
	 <head>
		 <title>You're Invited! Athletes Edge</title>
	 </head>
	 <body>
		<h2>Hello ".$name.",</h2>
		<p>We’re excited to let you know that you’ve been added to the group <strong>".$group."</strong> by Athletes Edge Team.</p>

		 <p>Thank you for joining us!</p>
		 <p>Best regards,<br>Athletes Edge Team</p>
	 </body>
	 </html>
 ";
	


	 $this->email->from($from_email,'Athletes Edge'); 
	 $this->email->to($to_email);
	 $this->email->subject('App Invitation'); 
	 $this->email->message($message); 
			  if($this->email->send()){
					  $response['sucess']=1;
	$response['msg']="Email has been Send";
//  	echo json_encode($response);    
//  exit;
// 	
		  }else{
		$response['sucess']=1;
	$response['msg']="Email not Send";
//	 echo json_encode($response);
	// echo 'Failed to send invitation email. Error: ' . $this->email->print_debugger();    
//exit;       
			  }

}

function sendemailforgernalinvation($email="adarvaish0@gmail.com",$name,$group,$subject){
    
	$config['protocol'] = 'smtp';
	$config['smtp_host'] = 'ssl://mail.buzzwaretech.com';
	$config['smtp_port'] = '465';
	$config['smtp_user'] ='genral@buzzwaretech.com';
	$config['smtp_pass'] = 'ebmacs12341@#$';  //sender's password
	$config['mailtype']    = 'html';
	$config['charset']     = 'utf-8';
	$config['newline']     = "\r\n";
	$config['wordwrap']    = TRUE;
	
	$this->load->library('email', $config);
	$this->email->initialize($config);
	
	 $to_email = $email;
	//  $to_email = "aonraza399@gmail.com";
	 $from_email = "genral@buzzwaretech.com";
	 $message = "
	 <html>
	 <head>
		 <title>You're Invited! Athletes Edge</title>
	 </head>
	 <body>
		<h2>Hello ".$name.",</h2>
		<p>We’re excited to let you know that you’ve been added to the group <strong>".$group."</strong> by Athletes Edge Team.</p>

		 <p>Thank you for joining us!</p>
		 <p>Best regards,<br>Athletes Edge Team</p>
	 </body>
	 </html>
 ";
	


	 $this->email->from($from_email,'Athletes Edge'); 
	 $this->email->to($to_email);
	 $this->email->subject($subject); 
	 $this->email->message($message); 
			  if($this->email->send()){
					  $response['sucess']=1;
	$response['msg']="Email has been Send";
//  	echo json_encode($response);    
//  exit;
// 	
		  }else{
		$response['sucess']=1;
	$response['msg']="Email not Send";
//	 echo json_encode($response);
	// echo 'Failed to send invitation email. Error: ' . $this->email->print_debugger();    
//exit;       
			  }

}




	public function addcustomer()
	{
		$this->template->template_render('adduser');
	}

	public function insertcustomer()
	{
		$post = $this->input->post();
		$post['isPro'] = $post['isPro']? true : false;
		$post['createdDate'] = time()*1000;
		$post['isActive'] = true;
		$post['userRole'] = 'user';
		$response = $this->customer_model->add_customer($post);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'New customer added successfully');
			redirect('customer');
		} else {
			$errormsg = 'Error! User already Exists.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect('customer/addcustomer');
		}
	}



	public function updatecustomer()
	{
		$da = $this->input->post();
		$da['isPro'] = $da['isPro']? true : false;
		$olddata=$this->customer_model->get_customerdetails($da['userId']);
		$oldTeamIds = array();
		$newTeamIds =  array();
		if(isset($olddata['teamId'])){
			$oldTeamIds=$olddata['teamId'];
		}
		$newTeamIds=$da['teamId'];

		if ($oldTeamIds === $newTeamIds) {
			// Do nothing if arrays are the same
//			echo "No changes detected.";
		} else {
			// Get new team IDs that don't exist in the old team IDs
			$addedTeamIds = array_diff($newTeamIds, $oldTeamIds);
			
			// Output the added team IDs
			if (!empty($addedTeamIds)) {
//				echo "New team IDs that are not in the old team IDs: ";
//				print_r($addedTeamIds);
				for($i=0;$i<count($addedTeamIds);$i++){
					
					$teamsdata=$this->common->readdatadocument('Teams', $addedTeamIds[$i]);
					$this->sendemailforinvationexitinguser($olddata['email'],$olddata['name'],$teamsdata['name']);
					


				}
				
			} else {
//				echo "No new team IDs found.";
			}
		}



		
		if ($da['password'] != "") {
			
			$flag = $this->customer_model->update_customerpassword($da['userId'], $da['password']);




			if ($flag) {
				$this->common->updatedatamodel("Users", $da['userId'], $da);
				$this->session->set_flashdata('successmessage', 'User has been updated successfully');
			} else {
				$this->session->set_flashdata('warningmessage', 'Something wrong, Please try again later');

				redirect(base_url().'customer/editcustomer/'.$da['userId']);
			}
		} else {
			$data["promotions"] = $this->common->updatedatamodel("Users", $da['userId'], $da);
			$this->session->set_flashdata('successmessage', 'User has been updated successfully');
		}



		redirect(base_url().'customer');
	}
	

	public function editcustomer()
	{
		$userId = $this->uri->segment(3);
		$data['userId'] = $userId;
		$data['user'] = $this->customer_model->get_customerdetails($userId);
		$data['teams'] = $this->common->readdatafromcollectionwhereclause('Teams');

		$this->template->template_render('adduser', $data);
	}

	public function coaches()
	{

		$data['customerlist'] = $this->customer_model->getall_coaches();
		// var_dump($data['customerlist']);die;
		// $data['customerlist'] = [];
		
		$this->template->template_render('coach_management', $data);
	}
	
	public function addcoach()
	{
		$data['teams'] = $this->common->readdatafromcollectionwhereclause('Teams');
		$this->template->template_render('addcoach',$data);
	}

	public function insertcoach()
	{
		$post = $this->input->post();
		$post['createdDate'] = time()*1000;
		$post['isActive'] = true;
		$response = $this->customer_model->add_coach($post);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'New customer added successfully');
			redirect('customer/coaches');
		} else {
			$errormsg = 'Error! User already Exists.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect('customer/addcoach');
		}
	}



	public function updatecoach()
	{
		$da = $this->input->post();
		
		if ($da['password'] != "") {
			
			$flag = $this->customer_model->update_customerpassword($da['coachId'], $da['password']);




			if ($flag) {
				$this->common->updatedatamodel("Coaches", $da['coachId'], $da);
				$this->session->set_flashdata('successmessage', 'Coach has been updated successfully');
			} else {
				$this->session->set_flashdata('warningmessage', 'Something wrong, Please try again later');

				redirect(base_url().'customer/editcustomer/'.$da['coachId']);
			}
		} else {
			$this->common->updatedatamodel("Coaches", $da['coachId'], $da);
			$this->session->set_flashdata('successmessage', 'Coach has been updated successfully');
		}



		redirect(base_url().'customer/coaches');
	}
	

	public function editcoach()
	{
		$coachId = $this->uri->segment(3);
		$data['coachId'] = $coachId;
		$data['coach'] = $this->customer_model->get_coachdetails($coachId);
		

		$this->template->template_render('addcoach', $data);
	}
//editTeams
public function editTeams()
{
	$coachId = $this->uri->segment(3);
	$data['teamId'] = $coachId;

	$data['teamsData'] = $this->common->readdatadocument('Teams', $coachId);
	$data["coachlist"] = $this->common->readdatafromcollectionbetween("Coaches");
	$data["memberlist"] = $this->common->readdatafromcollectionbetween("Users","userRole","=","user");
		

	$this->template->template_render('editteam', $data);
}
function addteam(){
	$data["coachlist"] = $this->common->readdatafromcollectionbetween("Coaches");
	$data["memberlist"] = $this->common->readdatafromcollectionbetween("Users","userRole","=","user");
		

	$this->template->template_render('addteam', $data);
}
public function addteamsdata(){
	$post = $this->input->post();
	$id=time().rand();
	$post['id']=$id;
	


		$this->common->adddatamodel("Teams", $post["id"], $post);

		$this->session->set_flashdata('successmessage', ' Teams Update successfully');
		redirect(base_url().'customer/teams/');

		
}
public function deleteteam()
{
$id = $this->uri->segment(3);

	$response = $this->common->deletedatamodel('Teams', $id);

if ($response) {
  $this->session->set_flashdata('successmessage', 'Teams deleted successfully..');
} else {
  $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
}

redirect(base_url('customer/teams'));
}


public function updateteamsdata(){
	$post = $this->input->post();
	$olddata=$this->common->readdatadocument('Teams', $post["id"]);

	$oldcoachIds = array();
	$newchoches =  array();
	if(isset($olddata['coachIds'])){
		$oldcoachIds=$olddata['coachIds'];
	}
	$newchoches=$post['coachIds'];
	if ($oldcoachIds === $newchoches) {
	}else{
		$addedCoachesds = array_diff($newchoches, $oldcoachIds);
		$jana=$addedCoachesds;
		$finallistofcoaches=array();
		foreach($addedCoachesds as $j){
			array_push($finallistofcoaches,$j);
		}
		for($k=0;$k<count($finallistofcoaches);$k++){
			if($finallistofcoaches[$k] !=""){
			//echo $finallistofmember[$k];
			//echo "<br>";
			$teamsdata=$this->common->readdatadocument('Coaches', $finallistofcoaches[$k]);
			// echo "<pre>";
			// print_r($teamsdata);
			// echo "</pre>";		
			$this->sendemailforgernalinvation($teamsdata['email'],$teamsdata['name'],$olddata['name'],"Team Invetation");
			}


	}
	}

	$oldmembersIds = array();
	$newmemberss =  array();
	if(isset($olddata['members'])){
		$oldmembersIds=$olddata['members'];
	}
	$newmemberss=$post['members'];

	if ($oldmembersIds === $newmemberss) {
		// Do nothing if arrays are the same
//			echo "No changes detected.";
	} else {
		// Get new team IDs that don't exist in the old team IDs
		$addedTeamIds = array_diff($newmemberss, $oldmembersIds);
		$jana=$addedTeamIds;
		$finallistofmember=array();
		foreach($addedTeamIds as $j){
			array_push($finallistofmember,$j);
		}



		
		for($k=0;$k<count($finallistofmember);$k++){
			if($finallistofmember[$k] !=""){
			//echo $finallistofmember[$k];
			//echo "<br>";
			$teamsdata=$this->common->readdatadocument('Users', $finallistofmember[$k]);
			// echo "<pre>";
			// print_r($teamsdata);
			// echo "</pre>";		
			$this->sendemailforgernalinvation($teamsdata['email'],$olddata['name'],$teamsdata['name'],"Team Invetation");
			}
	}
	
	}



	//print_r($olddata);

	


		$this->common->updatedatamodel("Teams", $post["id"], $post);

		$this->session->set_flashdata('successmessage', ' Teams Update successfully');
		redirect(base_url().'customer/editTeams/'.$post["id"]);

		
}

	public function freelancers()
	{

		$data['customerlist'] = $this->customer_model->getall_freelancers();
		
		$this->template->template_render('freelancer_management', $data);
	}
	public function addserviceprovider(){
		$data=array();
		$this->template->template_render('customer_add', $data);
	}

	public function teams()
	{

		$data['customerlist'] = $this->common->readdatafromcollectionwhereclause('Teams');
		
		$this->template->template_render('teams_management', $data);
	}
	public function userLogs()
	{
		$driverId = $this->uri->segment(3);

		$data['user'] = $this->common->readdatadocument('Users', $driverId);
		$this->template->template_render('userlogs', $data);
	}
	
	public function timesheet()
	{
		$driverId = $this->uri->segment(3);

		$data['user'] = $this->common->readdatadocument('Users', $driverId);
		$this->template->template_render('timesheet', $data);
	}
	public function documents()
	{
		$driverId = $this->uri->segment(3);

		$data['driver'] = $this->common->readdatadocument('Users', $driverId);
		$this->template->template_render('documents', $data);
	}

	
	function send_notification($token_id,$title,$body,$id,$type){
	 
		$icon=base_url('uploads/logo.png');
		
		$finalPostArray = array('registration_ids' => $token_id,
								'notification' => array('body' => $body,
														'title' => $title,
														"image"=> $icon,

													),
									'aps'=>array(
										"sound"=> "sample4_out.caf"
									),				
								"data"=> array(	"type"=>$type,
												"id"=>$id,
												"vibrate"=> 1)); 
		
	
		
		
		$headers = array
				(
					'Authorization: key=' . API_ACCESS_KEY1,
					'Content-Type: application/json'
				);
		#Send Reponse To FireBase Server	
		$ch = curl_init();
		curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
		curl_setopt( $ch,CURLOPT_POST, true );
		curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
		curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
		curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $finalPostArray ) );
		$result['mystatus'] = curl_exec($ch );
		curl_close( $ch );
		#Echo Result Of FireBase Server
		//$result['firbasestatus']=$fields;
		return $result;
	}

	public function sendWarning(){
		$post = $this->input->post();
		$c_id = $post['userid'];
		$message = $post['message'];
		$warning = $this->common->readdatadocument("Users",$c_id);
		$token='';
		if($warning['token']!=""){
			$token=$warning['token'];
		}

		if(!empty($token)){
			$notification=$this->send_notification($token,"System Warning",$message,"111",'systemWarning');

		}
		$extradata=array();
		$extradata['isread']=false;
		$extradata['notificationTime']=time()*1000;
		$extradata['songAddedBy']=NULL;
		$extradata['songId']=NULL;
		$extradata['songTitle']=NULL;
		$extradata['status']=false;
		$data["UserID"] = $c_id;
		$data["content"] = $message;
		$data["type"] = "Admin Warning";
		$data["isActive"] = true;
		$data['extradata']=$extradata;

		$response = $this->common->adddatamodel("Notification",time(),$data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Warning has been sent successfully');
			redirect('customer');
		} else {
			
			$this->session->set_flashdata('warningmessage', 'Something went wrong');
			redirect('customer');
		}


	}
	
	public function suspend()
	{
		
		$id = $this->uri->segment(3);

		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();
		$updatedUser = $auth->disableUser($id);

		
		if($updatedUser->disabled) {
			$data["isActive"] = false;
			$this->common->updatedatamodel("Users", $id, $data);

			// if(!empty($permissions)) {
				
			// 	$this->load->library('email');
			// 	$config = array();
					
			// 	$config['protocol'] = 'smtp';
			// 	$config['smtp_host'] = 'ssl://mail.buzzwaretech.com';
			// 	$config['smtp_user'] = 'testweb@buzzwaretech.com';
			// 	$config['smtp_pass'] = ',j8Og2d1Ty1%';
			// 	$config['smtp_port'] = 465; 
			// 	$config['mailtype'] = 'html';
			// 	$config['charset'] = 'iso-8859-1';
			// 	$config['wordwrap'] = 'TRUE';
			// 	$config['newline'] = "\r\n"; 
			// 	$this->email->initialize($config);
			// 	$this->email->set_newline("\r\n");
			// 	$from_email = "testweb@buzzwaretech.com"; 
			// 	$this->email->from($from_email, 'SongPad'); 
			// 	$this->email->to($user['email']);
			// 	$this->email->subject($suspended_subject);
			// 	$message = $suspended_text;
			// 	$this->email->message($message); 

			// 	$this->email->send();	

			// }
			$this->session->set_flashdata('successmessage', 'User has been suspended');
		}else{
			$this->session->set_flashdata('warningmessage', 'System Error: Please again later');
		}
		
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function reject()
	{
		
		$id = $this->uri->segment(3);

		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();
		$updatedUser = $auth->disableUser($id);

		
		if($updatedUser->disabled) {
			$data["rejected"] = true;
			$this->common->updatedatamodel("Users", $id, $data);

			$this->session->set_flashdata('successmessage', 'User has been rejected');
		}else{
			$this->session->set_flashdata('warningmessage', 'System Error: Please again later');
		}
		
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function approve()
	{
		$id = $this->uri->segment(3);
		$userRole = $this->uri->segment(4);
		
		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();
		$updatedUser = $auth->enableUser($id);

		if(!$updatedUser->disabled) {
			$data["isActive"] = true;
			$this->common->updatedatamodel("Users", $id, $data);
			
			$this->session->set_flashdata('successmessage', 'User Approved');
		}else{
			$this->session->set_flashdata('warningmessage', 'System Error: Please again later');
		}

		
		
			
		redirect($_SERVER['HTTP_REFERER']);
	}

	
	public function remove()
	{
		$id = $this->uri->segment(3);
		
		$response = $this->customer_model->delete_customer($id);
		if (!$response) {
			$this->session->set_flashdata('warningmessage', 'System Error: Please again later');
			redirect($_SERVER['HTTP_REFERER']);
			exit;
		}

		$response = $this->common->deletedatamodel("Users", $id);
		
		
		$this->session->set_flashdata('successmessage', ' Account Deleted');
		
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function removecoach()
	{
		$id = $this->uri->segment(3);
		
		$response = $this->customer_model->delete_customer($id);
		if (!$response) {
			$this->session->set_flashdata('warningmessage', 'System Error: Please again later');
			redirect($_SERVER['HTTP_REFERER']);
			exit;
		}

		$response = $this->common->deletedatamodel("Coaches", $id);
		
		
		$this->session->set_flashdata('successmessage', 'Coach Account Deleted');
		
		redirect($_SERVER['HTTP_REFERER']);
	}

	
}