<?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();
		
		
		$this->template->template_render('customer_management', $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 viewCustomer()
	{
		$c_id = $this->uri->segment(3);
		$data['id'] = $c_id;
		$data['customerdetails'] = $this->common->readdatadocument("Users", $id);
		echo "<pre>";
		print_r($data);
		echo "</pre>";
		exit;

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

	public function chatImages()
	{
		$chats = $this->common->readdatafromcollectionbetween('Chats');
		$chatImages = array();
		foreach($chats as $id => $chat) {
			$messages = $this->common->readdatacollection("Chats", "Conversations", $id);
			foreach($messages as $message) {
				if($message['type'] == 'image') {
					@$userFrom = $this->common->readdatadocument("Users", $message['fromID']);
					@$userFromName = $userFrom["firstName"]." ".$userFrom["lastName"];
					if(is_null($userFrom) || empty($userFrom)) {
						@$userFrom = $this->common->readdatadocument("DeletedUser", $message['fromID']);
						@$userFromName = "(Deleted User)<br>".$userFrom["firstName"]." ".$userFrom["lastName"]."<br>".$userFrom["phoneNumber"];
					}
					@$userTo = $this->common->readdatadocument("Users", $message['toID']);
					@$userToName = $userTo["firstName"]." ".$userTo["lastName"];
					if(is_null($userTo) || empty($userTo)) {
						@$userTo = $this->common->readdatadocument("DeletedUser", $message['toID']);
						@$userToName = "(Deleted User)<br>".$userTo["firstName"]." ".$userTo["lastName"]."<br>".$userTo["phoneNumber"];
					}

					$data = [
						'image' => $message['content'],
						'from' => $userFromName,
						'to' => $userToName,
					];
					array_push($chatImages, $data);
				}
			}
		}

		$data['chatImages'] = $chatImages;
		
		$this->template->template_render('chatimages', $data);
	}

	public function userLogs()
	{
		$uid = $this->uri->segment(3);
		$data['user'] = $this->customer_model->get_customerdetails($uid);
		
		$data['uid'] = $uid;
		// echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		//exit;
		$this->template->template_render('userlogs', $data);
	}

	public function suspendCustomer()
	{
$suspendeddata=$this->common->readdatafromcollectionbetween("Settings");
$s_data=$suspendeddata['70f5ced407934891b9fe'];
 $suspended_text=$s_data['accountsuspended_text'];
 $suspended_subject=$s_data['accountsuspended_subject'];

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

			$permissions = $this->session->userdata('session_data')['permissions'];
			if(!empty($permissions)) {
				$user = $this->common->readdatadocument("Users", $id);
				$adminName = $this->session->userdata('session_data')['name'];
				$adminEmail = $this->session->userdata('session_data')['email'];

				$auditData = [
					'adminName' => $adminName,
					'adminEmail' => $adminEmail,
					'time' => time(),
					'action' => "User Deactivated",
					'details' => $adminName." Deactivated a user with name ".$user['firstName']." ".$user['lastName']. " and email ".$user['email']
				];

				AddAuditLog($auditData);
				if(!empty($user['token'])){
					$notification=$this->send_notification($user['token'],"Your Account Terminated","This account has been terminated due to multiple violations of SongPad's Terms of Service","111",'systemWarning');
					$extradata=array();
					$extradata['isread']=false;
					$extradata['notificationTime']=time()*1000;
					$extradata['songAddedBy']=NULL;
					$extradata['songId']=NULL;
					$extradata['songTitle']=NULL;
					$extradata['status']=false;
					$notiData["UserID"] = $id;
					$notiData["content"] = "This account has been terminated due to multiple violations of SongPad’s Terms of Service";
					$notiData["type"] = "Account Terminated";
					$notiData["isActive"] = true;
					$notiData['extradata']=$extradata;

					$this->common->adddatamodel("Notification",time(),$notiData);
				}
				//send email to user
				$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 and notified');
		}else{
			$this->session->set_flashdata('warningmessage', 'User cannot be Suspended');
		}
	
		redirect(base_url().'customer');
	}

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

		if(!$updatedUser->disabled) {
			$data["isActive"] = true;
			$this->common->updatedatamodel("Users", $id, $data);
			$permissions = $this->session->userdata('session_data')['permissions'];
			if(!empty($permissions)) {
				$user = $this->common->readdatadocument("Users", $id);
				$adminName = $this->session->userdata('session_data')['name'];
				$adminEmail = $this->session->userdata('session_data')['email'];

				$auditData = [
					'adminName' => $adminName,
					'adminEmail' => $adminEmail,
					'time' => time(),
					'action' => "User Activated",
					'details' => $adminName." activated a user with name ".$user['firstName']." ".$user['lastName']. " and email ".$user['email']
				];

				AddAuditLog($auditData);	
			}
			$this->session->set_flashdata('successmessage', 'User Activated');
		}else{
			$this->session->set_flashdata('warningmessage', 'User cannot be Activated');
		}

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

	public function banCustomer()
	{
		$suspendeddata=$this->common->readdatafromcollectionbetween("Settings");
$s_data=$suspendeddata['70f5ced407934891b9fe'];
  $suspended_text=$s_data['accountterminated_text'];
  $suspended_subject=$s_data['accountterminated_subject'];

//exit;
		
		$id = $this->uri->segment(3);

		$data["isBanned"] = true;
		$response = $this->common->updatedatamodel("Users", $id, $data);

		$permissions = $this->session->userdata('session_data')['permissions'];
		if(!empty($permissions)) {
			$user = $this->common->readdatadocument("Users", $id);
			$adminName = $this->session->userdata('session_data')['name'];
			$adminEmail = $this->session->userdata('session_data')['email'];

			$auditData = [
				'adminName' => $adminName,
				'adminEmail' => $adminEmail,
				'time' => time(),
				'action' => "User Banned",
				'details' => $adminName." Banned a user with name ".$user['firstName']." ".$user['lastName']. " and email ".$user['email']
			];

			AddAuditLog($auditData);
			if(!empty($user['token'])){
				$notification=$this->send_notification($user['token'],"Your Account Terminated","This account has been terminated due to multiple violations of SongPad’s Terms of Service","111",'systemWarning');
				$extradata=array();
				$extradata['isread']=false;
				$extradata['notificationTime']=time()*1000;
				$extradata['songAddedBy']=NULL;
				$extradata['songId']=NULL;
				$extradata['songTitle']=NULL;
				$extradata['status']=false;
				$notiData["UserID"] = $id;
				$notiData["content"] = "This account has been terminated due to multiple violations of SongPad’s Terms of Service";
				$notiData["type"] = "Account Terminated";
				$notiData["isActive"] = true;
				$notiData['extradata']=$extradata;

				$this->common->adddatamodel("Notification",time(),$notiData);
			}

			$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->to('srtechs@gmail.com');
			$this->email->subject($suspended_subject);
			$message = $suspended_text;
			$this->email->message($message); 

			$this->email->send();
		}
		
		if($response) {

			$this->session->set_flashdata('successmessage', 'User has been banned and notified');
		}else{
			$this->session->set_flashdata('warningmessage', 'User cannot be Banned');
		}
		
		redirect(base_url().'customer');
	}

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

		$data["isBanned"] = false;
		$response = $this->common->updatedatamodel("Users", $id, $data);

		$permissions = $this->session->userdata('session_data')['permissions'];
		if(!empty($permissions)) {
			$user = $this->common->readdatadocument("Users", $id);
			$adminName = $this->session->userdata('session_data')['name'];
			$adminEmail = $this->session->userdata('session_data')['email'];

			$auditData = [
				'adminName' => $adminName,
				'adminEmail' => $adminEmail,
				'time' => time(),
				'action' => "User Unbanned",
				'details' => $adminName." Unbanned a user with name ".$user['firstName']." ".$user['lastName']. " and email ".$user['email']
			];

			AddAuditLog($auditData);	
		}
		
		if($response) {

			$this->session->set_flashdata('successmessage', 'User Unbanned');
		}else{
			$this->session->set_flashdata('warningmessage', 'User cannot be Unbanned');
		}

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

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

		$data["BannerImage"] = "";
		$response = $this->common->updatedatamodel("Users", $id, $data);

		$permissions = $this->session->userdata('session_data')['permissions'];
		if(!empty($permissions)) {
			$user = $this->common->readdatadocument("Users", $id);
			$adminName = $this->session->userdata('session_data')['name'];
			$adminEmail = $this->session->userdata('session_data')['email'];

			$auditData = [
				'adminName' => $adminName,
				'adminEmail' => $adminEmail,
				'time' => time(),
				'action' => "User Banner Removed",
				'details' => $adminName." Removed Banner of user with name ".$user['firstName']." ".$user['lastName']. " and email ".$user['email']
			];

			AddAuditLog($auditData);
			if(!empty($user['token'])){
				$notification=$this->send_notification($user['token'],"Your Banner Image Removed","Your Banner image was removed due to violation of SongPad’s guidelines for acceptable use","111",'systemWarning');
				$extradata=array();
				$extradata['isread']=false;
				$extradata['notificationTime']=time()*1000;
				$extradata['songAddedBy']=NULL;
				$extradata['songId']=NULL;
				$extradata['songTitle']=NULL;
				$extradata['status']=false;
				$notiData["UserID"] = $id;
				$notiData["content"] = "Your Banner image was removed due to violation of SongPad’s guidelines for acceptable use";
				$notiData["type"] = "Banner Removed";
				$notiData["isActive"] = true;
				$notiData['extradata']=$extradata;

				$this->common->adddatamodel("Notification",time(),$notiData);
			}
		}
		
		if($response) {

			$this->session->set_flashdata('successmessage', 'User Banner has been removed and user has been notified');
		}else{
			$this->session->set_flashdata('warningmessage', 'User Banner cannot be removed, please try again.');
		}

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

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

		$data["image"] = "";
		$response = $this->common->updatedatamodel("Users", $id, $data);

		$permissions = $this->session->userdata('session_data')['permissions'];
		if(!empty($permissions)) {
			$user = $this->common->readdatadocument("Users", $id);
			$adminName = $this->session->userdata('session_data')['name'];
			$adminEmail = $this->session->userdata('session_data')['email'];

			$auditData = [
				'adminName' => $adminName,
				'adminEmail' => $adminEmail,
				'time' => time(),
				'action' => "User Photo Removed",
				'details' => $adminName." Removed Photo of user with name ".$user['firstName']." ".$user['lastName']. " and email ".$user['email']
			];

			AddAuditLog($auditData);
			if(!empty($user['token'])){
				$notification=$this->send_notification($user['token'],"Your Profile Photo Removed","Your Profile Photo was removed due to violation of SongPad’s guidelines for acceptable use","111",'systemWarning');
				$extradata=array();
				$extradata['isread']=false;
				$extradata['notificationTime']=time()*1000;
				$extradata['songAddedBy']=NULL;
				$extradata['songId']=NULL;
				$extradata['songTitle']=NULL;
				$extradata['status']=false;
				$notiData["UserID"] = $id;
				$notiData["content"] = "Your Profile Photo was removed due to violation of SongPad’s guidelines for acceptable use";
				$notiData["type"] = "Photo Removed";
				$notiData["isActive"] = true;
				$notiData['extradata']=$extradata;

				$this->common->adddatamodel("Notification",time(),$notiData);
			}
		}
		
		if($response) {

			$this->session->set_flashdata('successmessage', 'User Profile Photo has been removed and user has been notified');
		}else{
			$this->session->set_flashdata('warningmessage', 'User Profile Photo cannot be removed, please try again.');
		}

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

	public function deleteCustomer()
	{
// 				$suspendeddata=$this->common->readdatafromcollectionbetween("Settings");
// $s_data=$suspendeddata['70f5ced407934891b9fe'];
//    $suspended_text=$s_data['accountdelete_subject'];

//    $suspended_subject=$s_data['accountdelete_text'];
  
		$id = $this->uri->segment(3);
		// $user = $this->common->readdatadocument("Users", $id);	
		// $this->common->adddatamodel("DeletedUser",$id,$user);
		
		$response = $this->customer_model->delete_customer($id);
		$response = true;
		if (!$response) {
			$this->session->set_flashdata('warningmessage', 'Something went wrong while deleting customer.');
			redirect(base_url().'customer');
			exit;
		}

		$response = $this->common->deletedatamodel("Users", $id);
		
		
		$this->session->set_flashdata('successmessage', 'Customer Deleted');
		redirect(base_url().'customer');
	}

	public function deleteLog()
	{
		$id = $this->uri->segment(3);
		$uid = $this->uri->segment(4);
		$this->common->deletedatamodel("Notification", $id);
		
		$this->session->set_flashdata('successmessage', 'Log Deleted');
		redirect(base_url().'customer/userLogs/'.$uid);
	}

	public function addcustomer()
	{
		$this->template->template_render('customer_add');
	}
	//editcustomer
	public function editcustomers($id)
	{


		$data['id'] = $id;echo($id);die;

		$data["customerdetails"] = $this->common->readdatadocument("Users", $id);

		$this->template->template_render('editcustomer', $data);
	}
	public function userreset()
	{
		$this->template->template_render('user_reset_credentials');
	}

	public function insertcustomer()
	{
		$data = $this->input->post();
		$data["role"] = "user";
		$data["city"] = NULL;
		$data["state"] = NULL;
		$data["token"] = NULL;
		$data["workAddress"] = NULL;
		$data["zipcode"] = NULL;
		$data["lat"] = 0;
		$data["lng"] = 0;
		$data["image"] = NULL;
		$data["clientSecret"] = NULL;
		$data["cusId"] = NULL;
		$data["ratings"] = NULL;
		$data["isApproved"] = TRUE;
		$data["isActive"] = true;

		$response = $this->customer_model->add_customer($data);
		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 updatecustomerdata($id)
	{
		$data = $this->input->post();
		//print_r($da);
		if ($data['password'] != "") {
			
			$flag = $this->customer_model->update_customerpassword($id, $data['password']);


			if ($flag) {
				$data['passReset'] = true;
				$this->common->updatedatamodel("Users", $id, $data);
				$permissions = $this->session->userdata('session_data')['permissions'];
				if(!empty($permissions)) {
					$user = $this->common->readdatadocument("Users", $id);
					$adminName = $this->session->userdata('session_data')['name'];
					$adminEmail = $this->session->userdata('session_data')['email'];

					$auditData = [
						'adminName' => $adminName,
						'adminEmail' => $adminEmail,
						'time' => time(),
						'action' => "Password Reset",
						'details' => $adminName." Reset the password of the user with name ".$user['firstName']." ".$user['lastName']. " and email ".$user['email']
					];

//					AddAuditLog($auditData);	
				}
				$this->session->set_flashdata('successmessage', 'User password has been updated, user need to reset it.');
				redirect(base_url().'customer');
			} else {
				$this->session->set_flashdata('warningmessage', 'Something wrong, Please try again later');

				redirect(base_url().'customer/editcustomer/'.$id);
			}
		} else {
			$this->session->set_flashdata('warningmessage', 'You need to enter new password.');

				redirect(base_url().'customer/editcustomer/'.$id);
		}
	}

	public function editcustomer()
	{
		$c_id = $this->uri->segment(3);
		$data['id'] = $c_id;
		$data['customerdetails'] = $this->customer_model->get_customerdetails($c_id);
		

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

	public function resetCustomer()
	{
		// $data = $this->input->post();
		foreach ($_POST as $key => $val) {
			if (strpos($key, "new") === 0) {
				$name = substr($key, 3);
				$data["new"][$name] = $val;
			}
		}
		foreach ($_POST as $key => $val) {
			if (strpos($key, "old") === 0) {
				$name = substr($key, 3);
				$data["old"][$name] = $val;
			}
		}
		// print_r($data);
		// exit;
		$response = $this->customer_model->update_customer($data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Customer updated successfully.');
			redirect('customer');
		} else {
			$errormsg = 'Error! Something went Wrong. Either the user does not exist or password does not match.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect('customer/userreset');
		}
	}

	public function updatecustomer()
	{
		$testxss = xssclean($_POST);
		if ($testxss) {
			$response = $this->customer_model->update_customer($this->input->post());
			if ($response) {
				$this->session->set_flashdata('successmessage', 'Customer updated successfully..');
				redirect('customer');
			} else {
				$this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
				redirect('customer');
			}
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Your input are not allowed.Please try again');
			redirect('customer');
		}
	}
}