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

class Users extends CI_Controller
{

	function __construct()
	{
		parent::__construct();
		$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', 'AAAAZPN-sfM:APA91bHo7Ncj4RB6Oo6qWkPsN6GjfblLeiGpuIGjCdZlFbbfHncOiCrDjzV2Nry9k_cOTmh-HD-VrXcXPJtCbWZR9E4gI6d-OfmVcgCg5VkQBH5yIxmVXbX0sJ93mQJVmgpdThkVPWKz');
	}


	public function index()
	{
		$data["users"] = $this->common->readdatafromcollectionwhereclause("Users","userRole","=","user");
		
		$this->template->template_render('customer_management', $data);
	}

	public function suspendCustomer($id)
	{
		$data["id"] = $id;
		$data["isApproved"] = False;
		$response = $this->common->updatedatamodel("Users", $data["id"], $data);
		$this->session->set_flashdata('successmessage', 'User Suspended');
		redirect('users');
	}

	public function updatemyprofile(){
		$data["firstName"] = $this->input->post('firstName');
		$data["lastName"] = $this->input->post('lastName');
		$data["email"] = $this->input->post('email');
		if($this->input->post('password') !=""){
			$data["password"] = $this->input->post('password');
		}
		$response = $this->common->updatedatamodel("Users", "CyFZrS4zNxHq0NaS2e3D", $data);
		$this->session->set_flashdata('successmessage', 'Profile has been update');
		redirect('users/profile');

	}


	public function unSuspendCustomer($id)
	{
		$data["id"] = $id;
		$data["isApproved"] = TRUE;
		$response = $this->common->updatedatamodel("Users", $data["id"], $data);
		$this->session->set_flashdata('successmessage', 'User UnSuspended');
		redirect('users');
	}

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

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

	public function profile($id="CyFZrS4zNxHq0NaS2e3D")
	{
		$data['id'] = $id;
		$data["client"] = $this->common->readdatadocument("Users", $id);
		$this->template->template_render('profile', $data);
	}
	public function delete_staff($id)
	{
		$flag = $this->customer_model->delete_customer($id);
		if ($flag) {
			$this->common->deletedatamodel("staff", $id);
			//$response = $this->common->deletedatamodel("preferredStaff", $id);
			$this->session->set_flashdata('successmessage', 'User Has Been  Deleted');
		} else {
			$this->common->deletedatamodel("staff", $id);
			//  $response = $this->common->deletedatamodel("preferredStaff", $id);
			$this->session->set_flashdata('successmessage', 'User Has Been  Deleted');
		}
		redirect(base_url() . '/staff');
	}

	public function delete_customer($id)
	{
		$flag = $this->customer_model->delete_customer($id);
		if ($flag) {
			$this->common->deletedatamodel("Users", $id);
			$response = $this->common->deletedatamodel("preferredStaff", $id);
			$this->session->set_flashdata('successmessage', 'User Has Been  Deleted');
		} else {
			$this->common->deletedatamodel("Users", $id);
			$response = $this->common->deletedatamodel("preferredStaff", $id);
			$this->session->set_flashdata('successmessage', 'User Has Been  Deleted');
		}
		redirect(base_url() . '/users');
	}

	public function deleteprefferlist($document, $document1)
	{
		$response = $this->common->nexteddeletedatamodel("preferredStaff", $document, "myclient", $document1);
		$this->session->set_flashdata('successmessage', 'Preffer User Deleted');
		redirect(base_url() . '/users/viewclient/' . $document . "/preferred");
	}

	
	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,
				"sound" => "default"
			),
			"data" => array(
				"click_action" => "FLUTTER_NOTIFICATION_CLICK",
				"type" => $type,
				"id" => $id,
				"sound" => "default",
				"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;
	}
	//editcustomer
	public function editcustomers($id)
	{


		$data['id'] = $id;

		$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['fullname']=$data['firstName']." ".$data['LastName'];
		$data["dob"] =strtotime($data['dob'])*1000;
		$data["employeestartdate"] =strtotime($data['employeestartdate'])*1000;
		$data["userRole"] = "user";
		$data["ratings"] = NULL;
		$data["userDate"] = time() * 1000;
		$data["isApproved"] = TRUE;
/*
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();
		if ($_FILES['image']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['image']['tmp_name']),
				[
					'name' => "UserImage/user" . rand() . time() . $_FILES['image']['name'],
				]
			);
			$data['image'] = $uploadedFile->info()['mediaLink'];
			print_r($uploadedFile->info());
		}
*/


		$response = $this->customer_model->add_customer($data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'New User added successfully');
			redirect(base_url() . 'Users');
		} else {
			$errormsg = 'Error! Client already Exists.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect(base_url() . 'users/adduser');
		}
	}


	public function updatecustomerdata($id)
	{
		$da = $this->input->post();
		$da['fullname']=$da['firstName']." ".$da['LastName'];
		$da["dob"] =strtotime($da['dob'])*1000;
		$da["employeestartdate"] =strtotime($da['employeestartdate'])*1000;
	
		if ($da['newpassword'] != "") {

			$da['password'] = $da['newpassword'];
			$da['newpassword'] = "";
			$flag = $this->customer_model->update_customerpassword($id, $da['password']);




			if ($flag) {
				$data["promotions"] = $this->common->updatedatamodel("Users", $id, $da);
				$this->session->set_flashdata('successmessage', 'Users has been updated successfully');
			} else {
				$this->session->set_flashdata('warningmessage', 'Usome thing error Please try later');

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



		redirect('users/editcustomers/' . $id);
	}

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


		$this->template->template_render('editcustomer', $data);
	}
	public function addstaffform($id)
	{
		$this->load->model('staff_model');
		$data = array();
		$data = $this->staff_model->get_allstaff();
		$data['id'] = $id;

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

	public function addprefencelistdata($clientId)
	{
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

		if ($_FILES['file']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['file']['tmp_name']),
				[
					'name' => "eliteImage" . rand() . time() . $_FILES['file']['name'],
				]
			);
			$data['fileLink'] = $uploadedFile->info()['mediaLink'];
			$data['fileName'] = $_FILES['file']['name'];
		}

		$data['clientID'] = $clientId;
		foreach ($this->input->post('staffs') as $key => $value) {
			$id = time();
			$data['staffID'] = $value;


			$this->common->adddatamodelnexted('preferredStaff', $clientId, "myclient", $id, $data);
		}
		redirect(base_url() . 'users/viewclient/' . $clientId . "/preferred");
	}

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