<?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()
	{
		$sessionData = $this->session->userdata('session_data');
		$data['customerlist'] = $this->customer_model->getall_customer();

		$data['userdetails'] = $sessionData;
		// echo '<pre>';	
		// print_r($data['customerlist']);
		// echo '<pre>';
		// die;	
		$this->template->template_render('customer_management', $data);
	}
	

	public function coaches()
	{
		$sessionData = $this->session->userdata('session_data');
		$data['customerlist'] = $this->customer_model->getall_trainer();

		// print_r($data['customerlist']);
		// die;
		$data['userdetails'] = $sessionData;		
		$this->template->template_render('coaches', $data);
	}

	public function add()
	{
		$sessionData = $this->session->userdata('session_data');
		// $data['customerlist'] = $this->customer_model->getall_trainer();

		// print_r($data['customerlist']);
		// die;
		$data['userdetails'] = $sessionData;		
		$this->template->template_render('add_owner', $data);
	}

	public function addOwner()
	{
		$this->form_validation->set_rules('name', 'Full Name', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('phone', 'Phone', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
		$this->form_validation->set_rules('photo', 'Photo', 'valid_url');
	
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect('customer/add');
		}
	
		$data = [
			'name' => $this->input->post('name'),
			'email' => $this->input->post('email'),
			'phone' => $this->input->post('phone'),
			'password' => $this->input->post('password'),
			// 'photo' => $this->input->post('photo'),
			'userType' => 'owner',
		];
	
		$result = $this->customer_model->add_owner($data);
	
		if ($result) {
			$this->session->set_flashdata('success', 'Owner added successfully.');
		} else {
			$this->session->set_flashdata('error', 'Failed to add owner.');
		}
	
		redirect('customer/add');
	}
	



	// public function survey()
	// {
	// 	$sessionData = $this->session->userdata('session_data');
	// 	// $data['customerlist'] = $this->customer_model->getall_freelancers();
	// 	$data['customerlist'] = $this->common->readdatafromcollectionwhereclause('Answers');
	// 	$data['questions'] = $this->common->readdatafromcollectionwhereclause('Questions', null, null);
	// 	$data['userdetails'] = $sessionData;
	// 	$this->template->template_render('survey', $data);
	// }

	public function drivers()
	{

		$data['customerlist'] = $this->customer_model->getall_drivers();

		$this->template->template_render('driver_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 test()
	{
		$weekInfo = $this->getCurrentWeekDates();

		echo "Week starts on: " . $weekInfo['startOfWeek'] . "\n";
		echo "Week ends on: " . $weekInfo['endOfWeek'] . "\n";
		echo "Dates in the week:\n";
		print_r($weekInfo['weekDates']);
	}

	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 deleteAnswer()
	{
		$id = $this->uri->segment(3);


		$response = $this->common->deletedatamodel("Answers", $id);


		$this->session->set_flashdata('successmessage', ' Answer Deleted');

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

	public function addQuestion()
	{
		$question = $this->input->post('question');


		$questionId = $this->generateUniqueId();

		$data = [
			'question' => $question
		];

		$response = $this->common->adddatamodel("Questions", $questionId, $data);

		if ($response) {
			$this->session->set_flashdata('successmessage', 'Question Added Successfully');
		} else {
			$this->session->set_flashdata('errormessage', 'Failed to Add Question');
		}

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

	private function generateUniqueId()
	{
		return uniqid(true);
	}

	public function updateQuestion()
	{
		$questionId = $this->input->post('id');
		$newQuestionText = $this->input->post('question');

		$data = [
			'question' => $newQuestionText
		];

		$response = $this->common->updatedatamodel("Questions", $questionId, $data);

		if ($response) {
			$this->session->set_flashdata('successmessage', 'Question Updated Successfully');
		} else {
			$this->session->set_flashdata('errormessage', 'Failed to Update Question');
		}

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

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


		$response = $this->common->deletedatamodel("Questions", $id);


		$this->session->set_flashdata('successmessage', ' Quuestion Deleted');

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