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

class Chat extends CI_Controller
{
	function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->library('session');
		$this->load->model('common');
		$this->load->model('customer_model');
	//	$this->load->database();
		$this->load->library(array('form_validation', 'template'));
	}

	public function index()
	{
		if (!function_exists('array_key_first')) {
			function array_key_first(array $arr)
			{
				foreach ($arr as $key => $unused) {
					return $key;
				}
				return NULL;
			}
		}

		$data["adminId"] = $this->session->userdata['session_data']['adminId'];
		$allcustomers = $this->customer_model->getall_customer();
		$data['chatUsers'] = $this->customer_model->get_chatcustomers();
		$firstUserId = array_key_first($data['chatUsers']);
		$data['firstUserId'] = $firstUserId;
		$data['userLastLogin'] = $data['chatUsers'][$firstUserId]['userLastLogin'];
		$data['userDisplayName'] = $data['chatUsers'][$firstUserId]['userName'];
		$data['allUsers'] = $allcustomers['user'];

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

	public function roomchat()
	{
		$data['admin'] = $this->common->readdatafromcollectionwhereclause("Users", "userRole", "=", "admin");
		$data['userlist'] = $this->common->readdatafromcollectionwhereclause("Users", "userRole", "!=", "admin");
		$data["adminId"] = array_keys($data['admin'])[0];
		$data['myrequest'] = $this->common->readdatafromcollectionwhereclause("Chats", "chatType", "=", "adminchat");

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

	public function deleteroomchat($id)
	{
		$data = $this->common->nextedreaddatafromcollectionwhereclause("Chats",  $id, "Conversations");
		foreach ($data as $key => $value) {
			$this->common->nexteddeletedatamodel("Chats", $id, "Conversations", $key);
		}
		$this->session->set_flashdata('successmessage', 'Chat has been removed successfully..');
		redirect('Chat/roomchat');
	}

	public function detailedroomchat($id)
	{
		$data['admin'] = $this->common->readdatafromcollectionwhereclause("Users", "userRole", "=", "admin");
		$data["adminId"] = array_keys($data['admin'])[0];
		$adminId = $data["adminId"];
		$data["conversation"] = $this->common->readdatacollection("Chats", "Conversations", $id);
		$data["chatId"] = $id;

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

	public function addnewroom()
	{
		$d = $this->common->readdatafromcollectionwhereclause("Users", "userRole", "=", "admin");
		$INSERTEDiD = time();

		$data['groupname'] = $this->input->post('groupname');
		$member = $this->input->post('members');
		$arrayName = array();
		$data["adminId"] = array_keys($d)[0];
		$arrayName[$data["adminId"]] = false;
		for ($i = 0; $i < count($member); $i++) {
			$arrayName[$member[$i]] = true;
		}

		$data['participants'] = $arrayName;
		$data["adminId"] = array_keys($d)[0];
		$data['createdBy'] = $INSERTEDiD;
		$data['conversationId'] = $INSERTEDiD;
		$data['lastmessage'] = "Admin Created this group";

		$papi = array();
		$papi['content'] = "Admin Added you in this group";
		$papi['fromID'] = $data["adminId"];
		$papi['messageId'] = $INSERTEDiD;
		$papi['timestamp'] = $INSERTEDiD;
		$papi['type'] = "text";

		$jawan['lastMessage'] = $papi;
		$jawan['chatType'] = "adminchat";
		$jawan['groupName'] = $data['groupname'];
		$jawan['participants'] = $arrayName;
		$this->common->adddatamodel("Chats", $INSERTEDiD, $jawan);
		$this->common->adddatamodelnexted("Chats", $INSERTEDiD, 'Conversations', $INSERTEDiD, $papi);

		redirect(base_url() . 'Chat/roomchat');
	}

	public function chatimageupload()
	{
		$thisClientID = $this->input->post('myid');

		$collectionName = 'Chats';
		$conversationID = $this->input->post('conversationId');
		$lastMessageID = $this->input->post('msgId');;

		$data = array();
		$data['image'] = $this->input->post('fileUrl');
		$data['fromID'] = $thisClientID;
		$data['isRead'] = false;
		$data['messageId'] = $lastMessageID;
		$data['timestamp'] = $lastMessageID;
		$data['type'] = 'image';
		$data['content'] = "";

		$res = $this->common->adddatamodelnexted($collectionName, $conversationID, 'Conversations', $lastMessageID, $data);

		echo (json_encode(array('status' => "OK", 'message' => "Image Uploaded", 'data' => $data, 'conversationID' => $conversationID)));
	}

	public function deletechat()
	{

		$chatID = $this->input->post('chatid');

		$res1 = $this->common->deletedatamodel('AdminChats', $chatID);

		echo (json_encode(array('status' => 'Success', 'message' => 'Chat Removed')));
	}

	public function detailedchat($id)
	{
		$data = $this->common->readdatadocument("AdminChat", $id);
		$data['admin'] = $this->common->readdatafromcollectionwhereclause("Users", "userRole", "=", "admin");
		$data["adminId"] = array_keys($data['admin'])[0];
		$adminId = $data["adminId"];
		$data["conversation"] = $this->common->readdatacollection("AdminChat", "Conversations", $id);
		foreach ($data["participants"] as $userId => $value) {
			if ($userId != $adminId) {
				$data["userId"] = $userId;
			}
		}
		$data["chatId"] = $id;
		$data["userName"] = $this->common->readusername($data["userId"]);
		$data["userImage"] = $this->common->readImage($data["userId"]);
		$this->template->template_render('chatdetails', $data);
	}

	public function Chatdetail($id)

	{
		$firebase = $this->firebase->init();
		$db = $firebase->createDatabase();
		$myid = $this->session->userdata('userdata')['user_id'];


		$support = $db->getReference("chat/" . $myid . '/' . $id)->getSnapshot()->getValue();
		$data['user'] = $db->getReference("User/" . $id)->getSnapshot()->getValue();
		$data['reciver_id'] = $id;
		$data['myid'] = $myid;
		// 	echo "<pre>";
		// 	print_r($data);
		// 	echo "</pre>";

		$this->load->view('bussiness/chat-detail', $data);
	}
}
