<?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'] = $this->customer_model->getall_customer();
		
		// var_dump($data['customerlist']);die;
		// $data['customerlist'] = [];
		
		$this->template->template_render('customer_management', $data);
	}
	public function vendors()
	{
		$data['customerlist'] = $this->customer_model->getall_vendor();
		
		$this->template->template_render('vendors', $data);
	}

	
	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');
	// $this->sendemailforinvation($data['email'],$data['teamId']);
	// echo "<pre>";
	// print_r($data);
	// echo "</pre>";
	// exit;



	$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'],$data['teamId'],$type);
		$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 myemailusing($email="adarvaish0@gmail.com",$teamid="accnj"){
	$email_encoded = urlencode($email);
$teamid_encoded = urlencode($teamid);
$link="https://athletesedge.page.link/userlogins?email=".$email_encoded."&teamid=".$teamid_encoded;
 $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>
	<a href='".$link."'>Join Now</a>
	<p>Thank you for joining us!</p>
	<p>Best regards,<br>Athletes Edge Team</p>
</body>
</html>
";
 $subject="App Invitation";
 $to="adarvaish0@gmail.com";	
$data = json_encode([
    "to" => "adarvaish0@gmail.com",  // You can also make 'to' dynamic
    "subject" => $subject,
    "message" => $message
]);
$curl = curl_init();



curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://us-central1-athletes-edge-95ced.cloudfunctions.net/widgets/send-email',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>$data,
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
var_dump($response) ;

}


function sendemailforinvation($email="adarvaish0@gmail.com",$teamid="",$type="user"){
	$email_encoded = urlencode($email);
	$teamid_encoded = urlencode($teamid);
	$link="";
	if($type=="user"){
		$link="https://athletesedge.page.link/userlogins?email=".$email_encoded."&teamid=".$teamid_encoded;
	}else{
		$link="https://athleteedgecoach.page.link/userlogins?email=".$email_encoded."&teamid=".$teamid_encoded;
	}
    
	//echo $link = str_replace(' ', '', $link);
	 $to_email = $email;
	 $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>
		 <a href='".$link."'>Join Now</a>
		 <p>Thank you for joining us!</p>
		 <p>Best regards,<br>Athletes Edge Team</p>
	 </body>
	 </html>
 ";
 $subject="App Invitation";
$data = json_encode([
    "to" => $email,  // You can also make 'to' dynamic
    "subject" => $subject,
    "message" => $message
]);
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://us-central1-athletes-edge-95ced.cloudfunctions.net/widgets/send-email',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>$data,
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);


/*
			  if($this->email->send()){
					  $res['sucess']=1;
	$res['msg']="Email has been Send";
		}else{
		$res['sucess']=1;
	$res['msg']="Email not Send";
	 }
*/
}

function sendemailforinvationexitinguser($email="adarvaish0@gmail.com",$name,$group){
    
	 $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>
 ";
	
 $subject="App Invitation";
$data = json_encode([
    "to" => $to_email,  // You can also make 'to' dynamic
    "subject" => $subject,
    "message" => $message
]);
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://us-central1-athletes-edge-95ced.cloudfunctions.net/widgets/send-email',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>$data,
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);




}

function sendemailforgernalinvation($email="adarvaish0@gmail.com",$name,$group,$subject){
    
	 $to_email = $email;

	 $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>
 ";

$data = json_encode([
    "to" => $to_email,  // You can also make 'to' dynamic
    "subject" => $subject,
    "message" => $message
]);
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://us-central1-athletes-edge-95ced.cloudfunctions.net/widgets/send-email',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>$data,
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
	

}




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

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


		$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('addinvitationcoach',$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);
		if(empty($data['user'])){
			$this->session->set_flashdata('warningmessage', 'User not found');
			redirect('customer');
		}
		if($data['user']['userRole'] == 'seller'){
		$data['experties'] = $this->common->readdatafromcollectionwhereclause('Services', 'userId', '=', $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);
		$userinfo=$this->common->readdatadocument("Users",$id);
		$email=$userinfo['email'];
		$myinvitationdata=$this->common->readdatafromcollectionbetween2where("Invitation","email","=",$email);
		foreach($myinvitationdata as $m=>$k){
			$this->common->deletedatamodel("Invitation", $m);
		}

		

		
		$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->common->deletedatamodel("Users", $id);
		
		$response = $this->customer_model->delete_customer($id);
		if (!$response) {
			$this->session->set_flashdata('warningmessage', 'System Error: Please again later');
			redirect($_SERVER['HTTP_REFERER']);
			exit;
		}


		
		
		$this->session->set_flashdata('successmessage', 'Coach Account Deleted');
		
		redirect($_SERVER['HTTP_REFERER']);
	}

	
}