<?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]['fullname'];
		$data['allUsers'] = $allcustomers['user'];

		
		$this->template->template_render('chat',$data); 
	}
	
	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);
	}



}