<?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 addRestaurant()
	{
		$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_restaurant', $data);
	}

	public function add_place_action()
	{
		$name = $this->input->post("name");
		$location = $this->input->post("location");
		$description = $this->input->post("description");
		$placeType = $this->input->post("placeType");
		$categoriesInput = $this->input->post("categories");
		$userId = $this->session->userdata('session_data')['userId'];

		$config['upload_path'] = './uploads/places/';
		$config['allowed_types'] = 'jpg|jpeg|png';
		$config['max_size'] = 2048;
		$config['file_name'] = uniqid('place_');

		$this->load->library('upload', $config);

		if (!$this->upload->do_upload('image')) {
			$this->session->set_flashdata('warningmessage', $this->upload->display_errors());
			redirect(base_url('customer/addRestaurant'));
		}

		$imageData = $this->upload->data();
		$imageUrl = base_url('uploads/places/' . $imageData['file_name']);

		$categories = [];
		if ($placeType === 'restaurant' || $placeType === 'groceries') {
			$categories = array_merge(['All Foods'], explode(',', $categoriesInput));
		}

		$firebase = $this->firebase->init();
		$db = $firebase->createFirestore()->database();

		$placeData = [
			'name' => $name,
			'userId' => $userId,
			'placeType' => $placeType,
			'rating' => 0.0,
			'description' => $description,
			'latitude' => '31.5497',
			'longitude' => '74.3436',
			'location' => $location,
			'imageUrl' => $imageUrl,
			'categories' => $categories,
		];

		try {
			$docRef = $db->collection('Places')->add($placeData);
			$placesId = $docRef->id();
			$docRef->update([
				['path' => 'placesId', 'value' => $placesId]
			]);

			$this->session->set_flashdata('successmessage', 'Place added successfully!');
			redirect(base_url('customer/addRestaurant'));
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Error adding place: ' . $e->getMessage());
			redirect(base_url('customer/addRestaurant'));
		}
	}

	// public function list_places()
	// {
	// 	$firebase = $this->firebase->init();
	// 	$db = $firebase->createFirestore()->database();

	// 	try {
	// 		$placesCollection = $db->collection('Places')->documents();

	// 		$places = [
	// 			'restaurant' => [],
	// 			'hotel' => [],
	// 			'groceries' => []
	// 		];

	// 		foreach ($placesCollection as $doc) {
	// 			$placeData = $doc->data();
	// 			$placeData['id'] = $doc->id(); // Store the Firestore document ID for edit/delete actions

	// 			if (isset($places[$placeData['placeType']])) {
	// 				$places[$placeData['placeType']][] = $placeData;
	// 			}
	// 		}

	// 		$data['places'] = $places;
	// 		// $this->load->view('places/list', $data);
	// 		$this->template->template_render('places_list', $data);
	// 	} catch (Exception $e) {
	// 		$this->session->set_flashdata('warningmessage', 'Error fetching places: ' . $e->getMessage());
	// 		redirect(base_url('dashboard'));
	// 	}
	// }

	public function edit_place($placeId)
	{
		$firebase = $this->firebase->init();
		$db = $firebase->createFirestore()->database();

		try {
			$docRef = $db->collection('Places')->document($placeId);
			$placeSnapshot = $docRef->snapshot();

			if ($placeSnapshot->exists()) {
				$data['place'] = $placeSnapshot->data();
				$data['place']['id'] = $placeId; // Include document ID
				$this->template->template_render('edit_restaurant', $data);
			} else {
				$this->session->set_flashdata('warningmessage', 'Place not found!');
				redirect(base_url('customer/list_places'));
			}
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Error fetching place: ' . $e->getMessage());
			redirect(base_url('customer/list_places'));
		}
	}


	public function update_place_action($placeId)
	{
		$name = $this->input->post("name");
		$description = $this->input->post("description");
		$location = $this->input->post("location");
		$placeType = $this->input->post("placeType");
		$categoriesInput = $this->input->post("categories"); // This is an array from the form
		$userId = $this->session->userdata('session_data')['userId'];

		$firebase = $this->firebase->init();
		$db = $firebase->createFirestore()->database();

		try {
			$docRef = $db->collection('Places')->document($placeId);

			// Prepare place data as key-value pairs
			$placeData = [
				['path' => 'name', 'value' => $name],
				['path' => 'description', 'value' => $description],
				['path' => 'location', 'value' => $location],
				['path' => 'placeType', 'value' => $placeType],
			];

			// Handle categories based on placeType
			if ($placeType === 'restaurant' || $placeType === 'groceries') {
				if (!empty($categoriesInput)) {
					// Process categories to ensure clean array
					$categories = explode(',', $categoriesInput); // Split by commas
					$categories = array_map('trim', $categories); // Trim whitespace
					$categories = array_filter($categories); // Remove empty values
					$categories = array_unique($categories); // Remove duplicates

					// Add "All Foods" if not already present
					if (!in_array('All Foods', $categories)) {
						array_unshift($categories, 'All Foods');
					}

					// Only add categories if there is a valid array
					$placeData[] = ['path' => 'categories', 'value' => $categories];
				} else {
					// Default to "All Foods" if no categories provided
					$placeData[] = ['path' => 'categories', 'value' => ['All Foods']];
				}
			} else {
				// For hotels, categories should be empty
				$placeData[] = ['path' => 'categories', 'value' => []];
			}

			// File upload logic
			if (!empty($_FILES['image']['name'])) {
				$config['upload_path'] = './uploads/places/';
				$config['allowed_types'] = 'jpg|jpeg|png';
				$config['max_size'] = 2048;
				$config['file_name'] = uniqid('place_');

				$this->load->library('upload', $config);

				if ($this->upload->do_upload('image')) {
					$imageData = $this->upload->data();
					$imageUrl = base_url('uploads/places/' . $imageData['file_name']);
					$placeData[] = ['path' => 'imageUrl', 'value' => $imageUrl];
				} else {
					$this->session->set_flashdata('warningmessage', $this->upload->display_errors());
					redirect(base_url('customer/edit_place/' . $placeId));
				}
			}

			// Update the Firestore document
			$docRef->update($placeData);
			$this->session->set_flashdata('successmessage', 'Place updated successfully!');
			redirect(base_url('customer/list_places'));
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Error updating place: ' . $e->getMessage());
			redirect(base_url('customer/edit_place/' . $placeId));
		}
	}


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

		$firebase = $this->firebase->init();
		$db = $firebase->createFirestore()->database();

		try {
			// Fetch menu items for the specific restaurant
			$menuItems = $db->collection('menu')->where('restaurantId', '=', $restaurantId)->documents();

			$data['menuItems'] = [];
			foreach ($menuItems as $item) {
				$data['menuItems'][] = $item->data();
			}
			$data['restaurantId'] = $restaurantId;

			$this->template->template_render('menu', $data);
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Error fetching menu items: ' . $e->getMessage());
			redirect(base_url('customer/list_places'));
		}
	}

	public function add_menu_item($restaurantId)
{
    $foodName = $this->input->post('foodName');
    $description = $this->input->post('description');
    $price = $this->input->post('price');
    $type = $this->input->post('type');
	$quantity = $this->input->post('quantity');
    $restaurantId = $this->input->post('restaurantId');
    
    // File upload logic for image
    $config['upload_path'] = './uploads/menu/';
    $config['allowed_types'] = '*';
    $config['max_size'] = 2048;
    $config['file_name'] = uniqid('menu_');
    
    $this->load->library('upload', $config);
    
    if (!$this->upload->do_upload('image')) {
        $this->session->set_flashdata('warningmessage', $this->upload->display_errors());
        redirect(base_url('customer/menu/' . $restaurantId));
    }
    
    $imageData = $this->upload->data();
    $imageUrl = base_url('uploads/menu/' . $imageData['file_name']);
    
    // Add menu item to Firestore
    $firebase = $this->firebase->init();
    $db = $firebase->createFirestore()->database();
    
    try {
        $menuItemData = [
            'foodName' => $foodName,
            'description' => $description,
            'price' => $price,
            'rating' => '0.0',
            'restaurantId' => $restaurantId,
            'imageUrl' => $imageUrl,
            'totalQuantity' => $quantity, 
			'type' => $type         
        ];
        
        // Add the new menu item to the Menu collection in Firestore
        $db->collection('menu')->add($menuItemData);
        $this->session->set_flashdata('successmessage', 'Menu item added successfully!');
        redirect(base_url('customer/menu/' . $restaurantId));
    } catch (Exception $e) {
        $this->session->set_flashdata('warningmessage', 'Error adding menu item: ' . $e->getMessage());
        redirect(base_url('customer/menu/' . $restaurantId));
    }
}









	public function list_places()
	{
		$firebase = $this->firebase->init();
		$db = $firebase->createFirestore()->database();

		// Get the logged-in user's ID from the session
		$userId = $this->session->userdata('session_data')['userId'];

		try {
			// Query Firestore to fetch only the places of the logged-in user
			$placesCollection = $db->collection('Places')->where('userId', '=', $userId)->documents();

			$places = [
				'restaurant' => [],
				'hotel' => [],
				'groceries' => []
			];

			foreach ($placesCollection as $doc) {
				$placeData = $doc->data();
				$placeData['id'] = $doc->id(); // Store the Firestore document ID for edit/delete actions

				if (isset($places[$placeData['placeType']])) {
					$places[$placeData['placeType']][] = $placeData;
				}
			}

			$data['places'] = $places;
			$this->template->template_render('places_list', $data);
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Error fetching places: ' . $e->getMessage());
			redirect(base_url('dashboard'));
		}
	}

	public function delete_place($placeId)
	{
		$firebase = $this->firebase->init();
		$db = $firebase->createFirestore()->database();

		try {
			$db->collection('Places')->document($placeId)->delete();
			$this->session->set_flashdata('successmessage', 'Place deleted successfully!');
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Error deleting place: ' . $e->getMessage());
		}

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




	// private function get_lat_lng($address)
	// {
	// 	$address = urlencode($address);
	// 	$apiKey = 'AIzaSyAhi3mFu4ntWNTYUERmA6KB361ziLX2vhE'; 
	// 	$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key={$apiKey}";

	// 	$response = file_get_contents($url);
	// 	$response = json_decode($response, true);

	// 	if (!empty($response['results'])) {
	// 		return [
	// 			'latitude' => $response['results'][0]['geometry']['location']['lat'],
	// 			'longitude' => $response['results'][0]['geometry']['location']['lng'],
	// 		];
	// 	}

	// 	return false;
	// }



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