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

use Google\Cloud\Firestore\FirestoreClient;

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 update_user()
	{
		$this->form_validation->set_rules('firstName', 'First Name', 'required');
		$this->form_validation->set_rules('lastName', 'Last Name', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		// $this->form_validation->set_rules('trashPoint', 'Trash Points', 'numeric');

		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect('customer');
		}

		$uid = $this->input->post('uid');

		$firebase = $this->firebase->init();
		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($this->config->item('firebase_app_key')), true)
		]);

		$userData = [
			'firstName' => $this->input->post('firstName'),
			'lastName' => $this->input->post('lastName'),
			'email' => $this->input->post('email'),
			'phoneNumber' => $this->input->post('phoneNumber'),
			// 'trashPoint' => (int)$this->input->post('trashPoint')
		];

		try {
			$docRef = $firestore->collection('Users')->document($uid);
			$docRef->set($userData, ['merge' => true]);

			$this->session->set_flashdata('success', 'User updated successfully.');
		} catch (Exception $e) {
			log_message('error', 'Firebase update_user error: ' . $e->getMessage());
			$this->session->set_flashdata('error', 'Failed to update user.');
		}

		redirect('customer');
	}




	// 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('terms', $data);
	// }

	public function terms()
	{
		$firebase = $this->firebase->init();
		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($this->config->item('firebase_app_key')), true)
		]);

		$docRef = $firestore->collection('settings')->document('terms_conditions');
		$snapshot = $docRef->snapshot();

		$data['terms'] = $snapshot->exists() ? $snapshot->data()['content'] : '';

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

	public function update_terms()
	{
		$this->form_validation->set_rules('content', 'Terms & Conditions', 'required');

		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect('customer/terms');
		}

		$firebase = $this->firebase->init();
		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($this->config->item('firebase_app_key')), true)
		]);

		$docRef = $firestore->collection('settings')->document('terms_conditions');
		$docRef->set(['content' => $this->input->post('content')]);

		$this->session->set_flashdata('success', 'Terms & Conditions updated successfully.');
		redirect('customer/terms');
	}


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

		$userRole = 'user';

		$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'),
			'userRole' => $userRole,
		];

		$result = $this->customer_model->add_owner($data);

		if ($result) {
			$this->session->set_flashdata('success', 'User added successfully.');
		} else {
			$this->session->set_flashdata('error', 'Failed to add User.');
		}

		redirect('customer');
	}

	public function activities($uid)
	{
		$firebase = $this->firebase->init();

		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($this->config->item('firebase_app_key')), true)
		]);

		// Get user's name
		$userDoc = $firestore->collection('Users')->document($uid)->snapshot();

		if (!$userDoc->exists()) {
			$this->session->set_flashdata('error', 'User not found.');
			redirect('customer/list'); // adjust if your route is different
		}

		$userData = $userDoc->data();
		$fullName = $userData['firstName'] . ' ' . $userData['lastName'];

		// Get activities
		$activitiesRef = $firestore->collection('VolunteerActivity');
		$query = $activitiesRef->where('userId', '=', $uid)->documents();

		$activities = [];

		foreach ($query as $doc) {
			if ($doc->exists()) {
				$data = $doc->data();
				$data['id'] = $doc->id(); // optional
				$activities[] = $data;
			}
		}

		$data['activities'] = $activities;
		$data['user_name'] = $fullName;

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




	public function avatar()
	{
		$sessionData = $this->session->userdata('session_data');

		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($this->config->item('firebase_app_key')), true)
		]);

		$documents = $firestore->collection('Avatar')->documents();

		$avatarsByCategory = [];

		foreach ($documents as $doc) {
			$avatar = $doc->data();
			$avatar['id'] = $doc->id(); // for update/delete
			$category = $avatar['category'];

			if (!isset($avatarsByCategory[$category])) {
				$avatarsByCategory[$category] = [];
			}

			$avatarsByCategory[$category][] = $avatar;
		}

		$data['avatars'] = $avatarsByCategory;
		$data['userdetails'] = $sessionData;

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

	// Add this to your admin controller

	public function addAvatar() {
		$this->load->library('firebase');
		
		$firebase = $this->firebase->init();
		$firestore = $firebase->createFirestore();
		$storage = $firebase->createStorage();
		$db = $firestore->database();
		$defaultBucket = $storage->getBucket();
	
		// $category = $this->input->post('category');
		// $unlockPoint = (int)$this->input->post('unlockPoint');
		// // $isPremium = $this->input->post('isPremium') ? true : false;
		// $isPremium = $this->input->post('isPremium') === 'true';

		$category = $this->input->post('category');
		$unlockPoint = (int)$this->input->post('unlockPoint');
		
		if ($category === 'Exclusive Avatars' || $category === 'Holiday Pack') {
			$isPremium = true;
		} else {
			$isPremium = false;
		}
		
		$imageUrl = '';

		if (!empty($_FILES['avatarImage']['name'])) {
			try {
				$file_name = 'Avatars/' . uniqid() . '_' . $_FILES['avatarImage']['name'];

				$uploadedFile = $defaultBucket->upload(
					file_get_contents($_FILES['avatarImage']['tmp_name']),
					['name' => $file_name, 'predefinedAcl' => 'publicRead']
				);
	
				if ($uploadedFile) {
					$imageUrl = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $file_name;
				}
			} catch (Exception $e) {
				echo json_encode(['success' => false, 'message' => 'Image upload failed: ' . $e->getMessage()]);
				return;
			}
		} else {
			echo json_encode(['success' => false, 'message' => 'Avatar image is required']);
			return;
		}
	
		// Save to Firestore
		try {
			$data = [
				'category' => $category,
				'isPremium' => $isPremium,
				'name' => $imageUrl,
				'unlockPoint' => $unlockPoint
			];
	
			$db->collection('Avatar')->add($data);
			
			echo json_encode(['success' => true, 'message' => 'Avatar added successfully']);
		} catch (Exception $e) {
			echo json_encode(['success' => false, 'message' => 'Firestore error: ' . $e->getMessage()]);
		}
	}
	
	public function updateAvatar() {
		$this->load->library('firebase');
		
		$firebase = $this->firebase->init();
		$firestore = $firebase->createFirestore();
		$storage = $firebase->createStorage();
		$db = $firestore->database();
		$defaultBucket = $storage->getBucket();
	
		$avatarId = $this->input->post('avatarId');
		$category = $this->input->post('category');
		$unlockPoint = (int)$this->input->post('unlockPoint');
		if ($category === 'Exclusive Avatars' || $category === 'Holiday Pack') {
			$isPremium = true;
		} else {
			$isPremium = false;
		}
	
		// Get current avatar data
		try {
			$avatarRef = $db->collection('Avatar')->document($avatarId);
			$currentAvatar = $avatarRef->snapshot()->data();
			$imageUrl = $currentAvatar['name'];
		} catch (Exception $e) {
			echo json_encode(['success' => false, 'message' => 'Failed to get current avatar data']);
			return;
		}
	
		// Handle file upload if present
		if (!empty($_FILES['avatarImage']['name'])) {
			try {
				// Generate unique file path in Avatars directory
				$file_name = 'Avatars/' . uniqid() . '_' . $_FILES['avatarImage']['name'];
	
				// Upload to Firebase Storage
				$uploadedFile = $defaultBucket->upload(
					file_get_contents($_FILES['avatarImage']['tmp_name']),
					['name' => $file_name, 'predefinedAcl' => 'publicRead']
				);
	
				if ($uploadedFile) {
					$imageUrl = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $file_name;
					
					// Optionally delete the old image from storage
					// Note: You would need to parse the old file path from the URL
				}
			} catch (Exception $e) {
				echo json_encode(['success' => false, 'message' => 'Image upload failed: ' . $e->getMessage()]);
				return;
			}
		}
	
		// Update Firestore document
		try {
			$data = [
				'category' => $category,
				'isPremium' => $isPremium,
				'name' => $imageUrl,
				'unlockPoint' => $unlockPoint
			];
	
			$avatarRef->set($data, ['merge' => true]);
			
			echo json_encode(['success' => true, 'message' => 'Avatar updated successfully']);
		} catch (Exception $e) {
			echo json_encode(['success' => false, 'message' => 'Firestore error: ' . $e->getMessage()]);
		}
	}
	
	public function deleteAvatar() {
		$this->load->library('firebase');
		
		$firebase = $this->firebase->init();
		$firestore = $firebase->createFirestore();
		$storage = $firebase->createStorage();
		$db = $firestore->database();
	
		$avatarId = $this->input->post('avatarId');
	
		try {
			// Optional: Get the avatar first to delete the associated image
			$avatarRef = $db->collection('Avatar')->document($avatarId);
			$avatar = $avatarRef->snapshot()->data();
			
			// Delete from Firestore
			$avatarRef->delete();
			
			// Optional: Delete the image from storage
			// You would need to parse the file path from the image URL
			// $imagePath = parseImagePathFromUrl($avatar['name']);
			// $bucket->object($imagePath)->delete();
			
			echo json_encode(['success' => true, 'message' => 'Avatar deleted successfully']);
		} catch (Exception $e) {
			echo json_encode(['success' => false, 'message' => 'Delete failed: ' . $e->getMessage()]);
		}
	}


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