<?php 
class Guardapi extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        // $this->load->model('Scheme_m');
       // $this->load->model('Scheme_m');
       date_default_timezone_set("Asia/Kolkata");
    }
    
    public function index()
    {
//       $userdata = json_decode(file_get_contents('php://input'),true);    
//       $this->db->where('username',$userdata['username']);
// 	   $this->db->where('password',$userdata['password']);
	   
// 	   $query=$this->db->get('Login_t');
//       if($query->num_rows() > 0)
// 	   {  
// 	        $rs = $query->row();
// 	        $userrights = $this->db->select('User_Id,Form_Name,Form_View')->where('User_Id',$rs->emp_id)->get('userright_t')->result();
	        
// 	        $data = array(
// 	                       "success"=>1,
// 	                       "userid"=>$rs->login_id,
// 	                       "usertype"=>$rs->usertyp,
// 	                       "fname"=>$rs->fname,
// 	                       "mname"=>$rs->mname,
// 	                       "lname"=>$rs->lname,
// 	                       "userrights"=>$userrights,
// 	                       "username"=>$rs->username,
// 	                       "email"=>$rs->emailid,
// 	                       "mobileno"=>$rs->mobileno,
// 	                       "address"=>$rs->address,
// 	                       "loginstatus"=>$rs->Login_Status
// 	                       //"quotation"=>$userrights->QUOT
// 	                     );
	                     
// 	                      $dataUnique = array("Unique_Token"=>$userdata['uniquetoken'],
// 	                                            "Login_Status"=>'1');
	   
// 	                      $this->db->where('username',$userdata['username'])->where('password',$userdata['password'])->update('Login_t',$dataUnique);
	   
// 			echo json_encode($data);
// 	   }
// 	   else{
// 	        echo json_encode(array("empty"=>0));
// 	   }
    }
    
    public function sendMsg() {
        $userdata = json_decode(file_get_contents('php://input'),true);
        
        $user = $this->db->where('Deleted_DT IS NULL')->where('id', $userdata['userid'])->get('mst_guard')->row();
        if(!empty($user)) {
            $data['guard_name'] = $userdata['userid'];
            $data['complaint_desc'] = $userdata['msg'];
            
    	    $data['inserted_by'] = $user->username;
    	    $data['inserted_SI'] = $userdata['userid'];
    	    $data['inserted_DT'] = date('Y-m-d H:i:s');
    	    
    	    $this->db->insert('mst_complaint', $data);
    	    
            $maxId = $this->db->select('max(comp_id) lastid')->where('guard_name', $userdata['userid'])->where('deleted_DT IS NULL')
                        ->get('mst_complaint')->result();


            $data['success'] = 1;
            $data['lastid'] = !empty($maxId[0]->lastid) ? $maxId[0]->lastid : '';
    	    
    	    
    	    echo json_encode($data);
        } else {
            echo json_encode(array('error'=> 0));
        }

        
    }
    

    public function receiveMsg() {
        $userdata = json_decode(file_get_contents('php://input'),true);
        
        $user = $this->db->where('Deleted_DT IS NULL')->where('id', $userdata['userid'])->get('mst_guard')->row();
      
        if(!empty($user)) {
            $whereLastCond = '';
            if(!empty($userdata['lastid'])) {
                $this->db->where(" comp_id > '{$userdata['lastid']}' ");
                // $whereLastCond = " comp_id > '{$userdata['lastid']}' ";
            }
            
            $chat = $this->db->where('guard_name', $userdata['userid'])->where('deleted_DT IS NULL')
                        ->order_by('comp_id', 'ASC')->get('mst_complaint')->result();

            $maxId = $this->db->select('max(comp_id) lastid')->where('guard_name', $userdata['userid'])->where('deleted_DT IS NULL')
                        ->get('mst_complaint')->result();


            $data['success'] = 1;
            $data['lastid'] = !empty($maxId[0]->lastid) ? $maxId[0]->lastid : '';
            $data['chats'] = $chat;
    	    
    	    echo json_encode($data);
        } else {
            echo json_encode(array('error'=> 0));
        }
    }
    
    public function get_todays_survey() {
        $userdata = json_decode(file_get_contents('php://input'),true);
        //check if userid is empty
        //check if todays survey is inserted already
        //else insert
        
        if(!empty($userdata['userid'])) {
            $surveyCheck = $this->db->where('inserted_SI',$userdata['userid'])->where("DATE(inserted_DT) = CURDATE()")->get('health_survey_ans')->result();
            if(empty($surveyCheck)) {
                $questions = $this->db->where('deleted_DT IS NULL')->get('health_survey_questions')->result();
                $data['questions'] =  $questions;
                echo json_encode($data);
            } else {
                echo json_encode(array('already_answered' => 1));
            }
            
        } else {
            echo json_encode(array('error' => 0));
        }
    }
    
    
    
     public function insertbocw()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        //   $check = $this->db->where('shop_name',$userdata['shopname'])->where('Deleted_DT',NULL)->get('tbl_naka')->result();
        //   if(count($check) > 0){
        //       echo json_encode(array("exist"=>0)); 
        //   } else {
         $uniqid = "";
            $query=$this->db->select_max('unique_id')->get('reg__new_docw')->row();
            $lastfour =  substr($query->unique_id, -5);
            $lastfour = $lastfour+1;
            $uniqid =  "0".$lastfour;
     
            

            if(!empty($userdata['aadharno']) && strlen(trim($userdata['aadharno'])) > 0) {
                $adharchk = $this->db->where('pd_aadhar', $userdata['aadharno'])->get('reg__new_docw')->result();
                if(count($adharchk) > 0) {echo json_encode(array('exist' => 0));exit; }
            }


            $dob = date('Y',strtotime($userdata['dob']));
            $current = date('Y');
            
            $age = $current - $dob;
            
            
             $data = array(
                   "pd_aadhar"=>$userdata['aadharno'],
                   "support_applicant_photo"=>$userdata['imagename'],
                   "unique_id"=>$uniqid,
                   "pd_fname"=>$userdata['firstname'],
                   "pd_mname"=>$userdata['middlename'],
                   "pd_lname"=>$userdata['lastname'],
                   "pd_city"=>$userdata['cityname'],
                   "pd_phone"=>$userdata['mobileno'],
                   "pd_age"=>$age,
                   "pd_gender"=>$userdata['gender'],
                   "pd_password"=>123456,
                   "status"=>0,
                   "pd_dob"=>date('Y-m-d',strtotime($userdata['dob'])),
                   "inserted_si"=>$userdata['userid'],
                   "inserted_by"=>$userdata['username'],
                   "inserted_date"=>date('Y-m-d H:i:S')
                  );
               
        if($this->db->insert('reg__new_docw',$data)) 
        {
            $newmessage = "Your registration number is: " . $uniqid;
           // $this->sendsms($newmessage, $userdata['mobileno']);
            echo json_encode(array("success" => 0, "uniqueid" => $uniqid )); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
      //}
    }
    
    
    public function get_count()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        $getcount = $this->db->where('Deleted_DT',NULL)->where('status','Active')->where('inserted_SI',$userdata['userid'])->get('mst_guard')->num_rows();
        
        $patientcount = $this->db->where('Deleted_DT',NULL)->where('inserted_SI',$userdata['userid'])->get('tr_assign_duty')->num_rows();
    
        if($patientcount > 0 && $getcount > 0 )
        {
            echo json_encode(array("success"=>0,"totcount"=>$getcount,"acount"=>$patientcount)); 
        }
        else if($patientcount > 0)
        {
            echo json_encode(array("success"=>0,"totcount"=>0,"acount"=>$patientcount)); 
        }
        else if($getcount > 0 )
        {
            echo json_encode(array("success"=>0,"totcount"=>$getcount,"acount"=>0)); 
        }
        else
        {
            echo json_encode(array("failed"=>0)); 
        }
    }
   
   
   public function change_password()
   {
       $userdata = json_decode(file_get_contents('php://input'),true);
       
       $data = array('password'=>$userdata['password'],'Modified_SI'=>$userdata['userid'],'Modified_BY'=>$userdata['username'],'Modified_DT'=>date('Y-m-d H:i:s'));
       
       if($this->db->where('login_id',$userdata['userid'])->update('login_t',$data))
       {
           echo json_encode(array("success"=>1)); 
       }
       else
       {
           echo json_encode(array("failed"=>0)); 
       }
       
   }
   
   
    
    public function assign_insertloc()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        $data=array("office_name"=>$userdata['office_name'],
					"guard_name"=>$userdata['guard_name'],
					"inserted_SI"=>$userdata['userid'],
                    "inserted_by"=>$userdata['username'],
                    "inserted_DT"=>date('Y-m-d H:i:s')
				);
        if($this->db->insert('tr_assign_duty',$data)) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
    }
    
    
     
    public function hospital_insert()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
          $getcount = $this->db->where('Deleted_DT',NULL)->where('contact',$userdata['contact'])->get('mst_hospital')->num_rows();
         if($getcount > 0){
               echo json_encode(array("already"=>1)); 
         } else {
        $data=array("hos_name"=>$userdata['hname'],
					"type"=>$userdata['type'],
					"area_name"=>$userdata['address'],
                    "contact"=>$userdata['contact'],
					"Latitude"=>$userdata['lat'],
					"Longitude"=>$userdata['log'],
					"Inserted_SI"=>$userdata['userid'],
                    "Inserted_BY"=>$userdata['username'],
                    "Inserted_DT"=>date('Y-m-d H:i:s')
				);
        if($this->db->insert('mst_hospital',$data)) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
    }
    }
    
    /* Created on 23 april 2020 for inserting contact with positive details*/
     public function insert_registration_update(){
        
        $userdata = json_decode(file_get_contents('php://input'),true);
         $getcount = $this->db->where('deleted_DT',NULL)->where('contact',$userdata['contact'])->get('mst_guard')->num_rows();
         if($getcount > 0){
              echo json_encode(array("already"=>1)); 
         } else {
              
        
		$data=array("name"=>$userdata['name'],
					"address"=>$userdata['address'],
					"email"=>$userdata['emailid'],
					"contact"=>$userdata['contact'],
					"DOB"=>date('Y-m-d',strtotime($userdata['DOB'])),
					"DOJ"=>date('Y-m-d',strtotime($userdata['DOJ'])),
					"age"=>$userdata['age'],
					"gender"=>$userdata['gender'],
					"type"=>$userdata['ptype'],
					"travel_from"=>$userdata['travel_from'],
					"travel_history"=>$userdata['history'],
					"information_source"=>$userdata['info'],
					"hospital_status"=>$userdata['hospital'],
					"hospital_name"=>$userdata['hname'],
					"migrate_status"=>$userdata['migration'],
					"migrate_state"=>$userdata['state'],
					"migrate_country"=>$userdata['country'],
					"patient_status"=>$userdata['pstatus'],
					"traceable"=>$userdata['treace'],
					"affected_country_leaving_dt"=>$userdata['lcdate'],
					"date_of_receipt_info"=>$userdata['ridate'],
					"date_of_hospitalisation"=>$userdata['hodate'],
					"username"=>$userdata['username'],
					"password"=>$userdata['password'],
					"status"=>'Active',
					"inserted_SI"=>$userdata['userid'],
                    "inserted_BY"=>$userdata['musername'],
                    "inserted_DT"=>date('Y-m-d H:i:s'),
                    "risk_type"=>$userdata['risktype'],
                    "location"=>$userdata['location'],
                    "relationship"=>$userdata['relation'],
                    "date_of_exposure"=>$userdata['exposuredt'],
                    "symptoms"=>$userdata['symptoms'],
                    "advised"=>$userdata['advised'],
                    "facility_name"=>$userdata['facilityname'],
                    "sample_taken"=>$userdata['sampletkn'],
                    "sample_date"=>$userdata['sampledate'],
                    "result"=>$userdata['result'],
                    "contact_person"=>$userdata['contperson'],
                    "person_id"=>$userdata['personid']
				);
				
    	 
        if($this->db->insert('mst_guard',$data)) 
        {
            $patientid = $this->db->select('id')->where('deleted_DT',NULL)->where('contact',$userdata['contact'])->get('mst_guard')->result();
            // $patientid = $this->db->insert_id();
             $data=array("Latitude"=>$userdata['lat'],
					"Longitude"=>$userdata['longt'],
					"Inserted_SI"=>$userdata['userid'],
                    "Inserted_BY"=>$userdata['musername'],
                    "Inserted_DT"=>date('Y-m-d H:i:s')
				);
            		if($this->db->insert('mst_office',$data)) 
                    {
                         $locid = $this->db->select('id')->where('deleted_DT',NULL)->order_by('id', 'DESC')->where('Inserted_SI',$userdata['userid'])->get('mst_office')->result();
                       
                               // $locid = $this->db->insert_id(); 
                                 $data=array("office_name"=>$locid[0]->id,
                					"guard_name"=>$patientid[0]->id,
                					"inserted_SI"=>$userdata['userid'],
                                    "inserted_by"=>$userdata['musername'],
                                    "inserted_DT"=>date('Y-m-d H:i:s')
                				);
                        if($this->db->insert('tr_assign_duty',$data)) 
                        {
                            echo json_encode(array("success"=>1));
                            exit;
                        }else{
                            echo json_encode(array("failed"=>0)); 
                            exit;
                        }
                
                  } else{
                        echo json_encode(array("failed"=>0)); 
                        exit;
                }
    	    
        } else{
            echo json_encode(array("failed"=>0)); 
             exit;
        }
      } 
	}
   
     
     public function insert_registration_new(){
        
        $userdata = json_decode(file_get_contents('php://input'),true);
         $getcount = $this->db->where('deleted_DT',NULL)->where('contact',$userdata['contact'])->get('mst_guard')->num_rows();
         if($getcount > 0){
              echo json_encode(array("already"=>1)); 
         } else {
              
        
		$data=array("name"=>$userdata['name'],
					"address"=>$userdata['address'],
					"email"=>$userdata['emailid'],
					"contact"=>$userdata['contact'],
					"DOB"=>date('Y-m-d',strtotime($userdata['DOB'])),
					"DOJ"=>date('Y-m-d',strtotime($userdata['DOJ'])),
					"age"=>$userdata['age'],
					"gender"=>$userdata['gender'],
					"type"=>$userdata['ptype'],
					"travel_from"=>$userdata['travel_from'],
					"travel_history"=>$userdata['history'],
					"information_source"=>$userdata['info'],
					"hospital_status"=>$userdata['hospital'],
					"hospital_name"=>$userdata['hname'],
					"migrate_status"=>$userdata['migration'],
					"migrate_state"=>$userdata['state'],
					"migrate_country"=>$userdata['country'],
					"patient_status"=>$userdata['pstatus'],
					"traceable"=>$userdata['treace'],
					"affected_country_leaving_dt"=>$userdata['lcdate'],
					"date_of_receipt_info"=>$userdata['ridate'],
					"date_of_hospitalisation"=>$userdata['hodate'],
					"username"=>$userdata['username'],
					"password"=>$userdata['password'],
					"status"=>'Active',
					"inserted_SI"=>$userdata['userid'],
                    "inserted_BY"=>$userdata['musername'],
                    "inserted_DT"=>date('Y-m-d H:i:s')
				);
				
    	    
        if($this->db->insert('mst_guard',$data)) 
        {
             $patientid = $this->db->insert_id();
             
             $data=array("Latitude"=>$userdata['lat'],
					"Longitude"=>$userdata['longt'],
					"Inserted_SI"=>$userdata['userid'],
                    "Inserted_BY"=>$userdata['musername'],
                    "Inserted_DT"=>date('Y-m-d H:i:s')
				);
            		if($this->db->insert('mst_office',$data)) 
                    {
                                $locid = $this->db->insert_id(); 
                                 $data=array("office_name"=>$locid,
                					"guard_name"=>$patientid,
                					"inserted_SI"=>$userdata['userid'],
                                    "inserted_by"=>$userdata['musername'],
                                    "inserted_DT"=>date('Y-m-d H:i:s')
                				);
                        if($this->db->insert('tr_assign_duty',$data)) 
                        {
                            echo json_encode(array("success"=>1));
                            exit;
                        }else{
                            echo json_encode(array("failed"=>0)); 
                            exit;
                        }
                
                  } else{
                        echo json_encode(array("failed"=>0)); 
                        exit;
                }
    	    
        } else{
            echo json_encode(array("failed"=>0)); 
             exit;
        }
      } 
	}
   
     
     
     public function insert_registration(){
        
        $userdata = json_decode(file_get_contents('php://input'),true);
         $getcount = $this->db->where('deleted_DT',NULL)->where('contact',$userdata['contact'])->get('mst_guard')->num_rows();
         if($getcount > 0){
              echo json_encode(array("already"=>1)); 
         } else {
             
             if((strtotime($userdata['DOB']) > strtotime(date('Y-m-d')))  || (strtotime($userdata['DOJ']) > strtotime(date('Y-m-d')))) {
                echo json_encode(array("failed"=>0));
                exit;
            } 
        
		$data=array("name"=>$userdata['name'],
					"address"=>$userdata['address'],
					"email"=>$userdata['emailid'],
					"contact"=>$userdata['contact'],
					"DOB"=>date('Y-m-d',strtotime($userdata['DOB'])),
					"DOJ"=>date('Y-m-d',strtotime($userdata['DOJ'])),
					"age"=>$userdata['age'],
					"gender"=>$userdata['gender'],
					"type"=>$userdata['ptype'],
					"travel_from"=>$userdata['travel_from'],
					"travel_history"=>$userdata['history'],
					"information_source"=>$userdata['info'],
					"hospital_status"=>$userdata['hospital'],
					"hospital_name"=>$userdata['hname'],
					"migrate_status"=>$userdata['migration'],
					"migrate_state"=>$userdata['state'],
					"migrate_country"=>$userdata['country'],
					"patient_status"=>$userdata['pstatus'],
					"username"=>$userdata['username'],
					"password"=>$userdata['password'],
					"status"=>'Active',
					"inserted_SI"=>$userdata['userid'],
                    "inserted_BY"=>$userdata['musername'],
                    "inserted_DT"=>date('Y-m-d H:i:s')
				);
        if($this->db->insert('mst_guard',$data)) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
      } 
	}
   


   public function showdropdown()
   {
        $userdata = json_decode(file_get_contents('php://input'),true);

        $location = $this->db->select('id as officeid,name')->where('Inserted_SI',$userdata['userid'])->where('deleted_DT',NULL)->order_by('id',"desc")->get('mst_office')->result();

        $patientarray = array();
       /* $patientlist = $this->db->select('id,name')->where('Inserted_SI',$userdata['userid'])->where('status','Active')->where('deleted_DT',NULL)->order_by('id',"desc")->get('mst_guard')->result();*/
        $patientlist = $this->db->select('id,name')->where('Inserted_SI',$userdata['userid'])->where('deleted_DT',NULL)->order_by('id',"desc")->get('mst_guard')->result();
// echo $patientlist->num_rows();exit;
        $i = 0;
        foreach($patientlist as $disp){
            $chkemp = $this->db->select('guard_name')->where('guard_name',$disp->id)->where('deleted_DT',NULL)->get('tr_assign_duty')->result();
            if(count($chkemp) == 0)
            {
                    $patientarray[$i]['id'] = $disp->id;            
                    $patientarray[$i]['name'] = $disp->name;            
                    $i++;
            }
        }
        
        // print_r($patientarray);
        
        // exit;
        if($location > 0 && $patientlist > 0)
        {
            echo json_encode(array("success"=>1,"locationlist"=>$location,"patientlist"=>$patientarray)); 
        }
        else
        {
            echo json_encode(array("failed"=>0)); 
        }
    }
      

   
    
    public function insertnaka()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
          $check = $this->db->where('mobile_no',$userdata['mobileno'])->where('Deleted_DT',NULL)->get('tbl_naka')->result();
          if(count($check) > 0){
               echo json_encode(array("exist"=>0)); 
          } else {
                 $data = array(
                       "shop_name"=>$userdata['shopname'],
                       "person_name"=>$userdata['personname'],
                       "mobile_no"=>$userdata['mobileno'],
                       "city"=>$userdata['city'],
                       "latitude"=> $userdata['latitude'],
                       "longitude"=> $userdata['longitude'],
                       "landmark"=>$userdata['landmark'],
                       "address"=>$userdata['address'],
                       "Inserted_SI"=>$userdata['userid'],
                       "Inserted_BY"=>$userdata['username'],
                       "Inserted_DT"=>date('Y-m-d H:i:S')
                      );
        if($this->db->insert('tbl_naka',$data)) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
      }
    }
    
    public function insert_user_survey() {
        $userdata = json_decode(file_get_contents('php://input'),true);
        //check if userid is empty
        //check if todays survey is inserted already
        //else insert
        
        if(!empty($userdata['userid'])) {
            // SELECT * FROM `mst_complaint` WHERE DATE(inserted_DT) = CURRENT_DATE
            $surveyCheck = $this->db->where('inserted_SI',$userdata['userid'])->where("DATE(inserted_DT) = CURDATE()")->get('health_survey_ans')->row();
            
            $user = $this->db->where('Deleted_DT IS NULL')->where('id', $userdata['userid'])->get('mst_guard')->row();
            
            
            if(empty($surveyCheck)) {
                if(!empty($userdata['answers'])) {
                    foreach($userdata['answers'] as $ans) {
                        $data['questionid'] = $ans['questionid'];
                        $data['answer'] = !empty($ans['answer']) ? $ans['answer'] : 0;
                        $data['Inserted_SI'] = $user->id;
                        $data['inserted_BY'] = $user->username;
                        $data['inserted_DT'] = date('Y-m-d H:i:s');
                        
                        
                        $this->db->insert('health_survey_ans', $data);
                    }    
                    echo json_encode(array('success' => 1));
                }
                
            } else {
                echo json_encode(array('already_answered' => 1));
            }
            
        } else {
            echo json_encode(array('error' => 0));
        }
        
    }
    
    
    function home()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        
        $guardinfo = $this->db->select('status,name,id')->where('id',$userdata['userid'])->get('mst_guard')->row();
        if(count($guardinfo)>0){
        
        $latestofficeid = $this->db->select('office_name')->where('guard_name',$guardinfo->id)->order_by('d_id','desc')->get('tr_assign_duty')->row();
        
        $annoucement = $this->db->where('a_office', $latestofficeid->office_name)->or_where('type', 'all')->order_by('a_id', 'DESC')->limit(5)->get('announcement')->result();
        
        if(count($guardinfo)>0 && count($latestofficeid)>0 && count($annoucement)>0)
        {
            $data = json_encode(array( 
                               "guard_status"=>$guardinfo->status,
                               "office_id"=>$latestofficeid->office_name,
                               "announcement"=>$annoucement
                             ));
                             
            if($guardinfo->status!='' && $latestofficeid->office_name!='' && count($annoucement)>0) {
                echo $data;exit;
            } else {
                echo json_encode(array('failed' => 0));exit;
            }
        }
        else
        {
            echo json_encode(array('failed' => 0));exit;
        }
        }else
        {
            echo json_encode(array('failed' => 0));exit;
        }
        
    }
   
    
    function showdashboard() {
        
        $userdata = json_decode(file_get_contents('php://input'),true);
     
                       
        if($userdata['userid']!='')
        {   
            $updtToken = array('Token'=> $userdata['token']);
            $this->db->where('login_id', $userdata['userid'])->update('login_t', $updtToken);
            
            $notifications = $this->db->where('etype', 1)->order_by('Inserted_DT', 'DESC')->limit(5, 0)->get('push_notification')->result_array();

             $nakacount = $this->db->where('inserted_si',$userdata['userid'])->where('deleted_dt',NULL)->get('tbl_naka')->num_rows();
             $registercount = $this->db->where('inserted_si',$userdata['userid'])->where('deleted_dt',NULL)->get('reg__new_docw')->num_rows();
             
             if(count($nakacount)>0)
             {
                $ncount = $nakacount;
             }
             else
             {
                 $ncount=0;
             }
             
             if(count($registercount)>0)
             {
                $regcount = $registercount;
             }
             else
             {
                 $regcount=0;
             }
            
               
            $data = array( 
                           "success"=>1,
                           "count_naka"=>$ncount,
                           "count_registration"=>$regcount,
                           "notifications" => $notifications
                         );
            echo json_encode($data);
            
        }else{
            
            echo json_encode(array("failed"=>0));
        }     
    }
    
    public function loginguard()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);  
    //join('scheme_master sm', 'sm.id = us.schemes')->where('us.userid', $userdata['userid'])->get('user_schemes us')->result_array();
        if($userdata['username'] !='' && $userdata['password']!='')
        {
           
           $rs  = $this->db->select('mg.*, sm.office_name')
                        ->join('tr_assign_duty sm', 'sm.guard_name = mg.id', 'left')
                        ->where('mg.username',$userdata['username'])
	                    ->where('mg.password',$userdata['password'])
                        ->where('mg.Deleted_DT',NULL)
                        ->where('mg.status','Active')
                        ->order_by('sm.d_id','DESC')
                        ->limit(1)
                        ->get('mst_guard mg')
                        ->result();
        }    
        if(count($rs) > 0)
        {
                $enquiryfollowup['guard_detail'] = $rs;
                echo json_encode($enquiryfollowup);
        }else{
           echo json_encode(array("empty"=>0)); 
        }
    }
    
    public function insert_office()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);  
        
        $data=array("name"=>$userdata['name'],
					"address"=>$userdata['address'],
					"email"=>$userdata['emailid'], 
					"contact"=>$userdata['contact'], 
					"city"=>$userdata['city'],
					"Latitude"=>$userdata['longitude'],
					"Longitude"=>$userdata['latitude'],
					"Inserted_SI"=>$userdata['userid'],
                    "Inserted_BY"=>$userdata['username'],
                    "Inserted_DT"=>date('Y-m-d H:i:s')
				);
		if($this->db->insert('mst_office',$data)) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
        
    }
    
    
    public function loginemployee()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);  
    
            if($userdata['username'] !='' && $userdata['password']!='')
        {
           $rs = $this->db->select('*')
                        ->where('username',$userdata['username'])
	                    ->where('password',$userdata['password'])
                        ->where('deleted_dt',NULL)
                        ->get('login_t')
                        ->result();
        }            
        if(count($rs)>0)
        {
                $empdata['employee'] = $rs;
                echo json_encode($empdata);
        }else{
           echo json_encode(array("empty"=>0)); 
        }
    }

    
    // public function insert_contact() {
    //     $userdata = json_decode(file_get_contents('php://input'),true);
    
    //     if(count($userdata)>0)
    //     {
    //         foreach($userdata['contactlist'] as $name)
    //         {
    //                     $data['user_id'] = $name['user_id'];
    //                     $data['number'] = $name['number'];
    //                     $data['name'] = $name['name'];
    //                     $data['inserted_BY'] = $name['name'];
    //                     $data['inserted_DT'] = date('Y-m-d H:i:s');
    //                     $this->db->insert('tbl_contact', $data);
    //         }
    //         echo json_encode(array('success' => 1));
    //     }
    //     else
    //     {
    //         echo json_encode(array('error' => 0));        
    //     }
            
    // }
    
    
    public function officelist()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        
        $rs = $this->db->select('*')->where('Deleted_DT',NULL)->where('Inserted_SI',$userdata['userid'])->order_by('id','DESC')->get('mst_office')->result();
        
        if(count($rs) > 0)
        {
            foreach($rs as $row)
            {
                $refference['officelist'][] = $row;
            }
            echo json_encode($refference);
        }else{
            
           echo json_encode(array("empty"=>0)); 
        }
    }
    
    
    
    public function insert_complaint()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
         
                 $data = array(
                       "guard_name"=>$userdata['gid'],
                       "mobile_no"=>$userdata['mobile'],
                       "office"=>$userdata['offid'],
                       "complaint"=>$userdata['title'],
                       "complaint_desc"=> $userdata['desc'],
                       "inserted_by"=>$userdata['userid'],
                       "inserted_SI"=>$userdata['username'],
                       "inserted_DT"=>date('Y-m-d H:i:S')
                      );
        if($this->db->insert('mst_complaint',$data)) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
      
    }
    
    
      
    public function insert_location()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
         
        foreach($userdata['loclist'] as $row)
    	{
                 $data = array(
                       "guard_id"=>$row['gid'],
                       "office_id"=>$row['officeid'],
                       "attendance_id"=> $row['aid'],
                       "datetime"=>$row['datetime'],
                       "LAT"=>$row['lat'],
                       "LONGI"=> $row['log'],
                       "area"=> $row['area'],
                       "popup_count"=> $row['pcount'],
                       "inserted_by"=>$row['userid'],
                       "inserted_SI"=>$row['username'],
                       "inserted_DT"=>date('Y-m-d H:i:S')
                      );
                      
                $return = $this->db->insert('guard_location',$data);               
    	}              
        if($return) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
        
      
    }
    
    
    public function insert_attendance(){
        
        $userdata = json_decode(file_get_contents('php://input'),true);
        
        if($userdata['aid'] == 0) {
           $data = array(
                       "guard_id"=>$userdata['gid'],
                       "office_id"=>$userdata['officeid'],
                       "PI_DT"=> $userdata['datetime'],
                       "PI_LAT"=>$userdata['lat'],
                       "PI_LONG"=> $userdata['log'],
                       "PI_area"=> $userdata['area'],
                       "inserted_BY"=>$userdata['userid'],
                       "inserted_SI"=>$userdata['username'],
                       "inserted_DT"=>date('Y-m-d H:i:S')
                      );
        if($this->db->insert('attendence',$data)) 
        {
           $id = $this->db->insert_id();
            echo json_encode(array("success"=>1, 'id'=> $id)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
        } else {
              $data = array(
                       "guard_id"=>$userdata['gid'],
                       "office_id"=>$userdata['officeid'],
                       "PO_DT"=> $userdata['datetime'],
                       "PO_LAT"=>$userdata['lat'],
                       "PO_LONG"=> $userdata['log'],
                       "PO_area"=> $userdata['area'],
                       "modify_BY"=>$userdata['userid'],
                       "modify_SI"=>$userdata['username'],
                       "modify_DT"=>date('Y-m-d H:i:S')
                      );
        if($this->db->where('a_id', $userdata['aid'])->update('attendence',$data)) 
        {
            echo json_encode(array("success"=>1, 'id'=>0)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
        }
    }
    
       
     public function getannouncement() {
      
        $userdata = json_decode(file_get_contents('php://input'),true);
      /*   if($userdata['officeid'] == ''){*/
            $result = $this->db->where('type', 'all')->where('Deleted_DT',NULL)->order_by('a_id', 'DESC')->get('announcement')->result_array();
        /* } else {
              $result = $this->db->where('Deleted_DT',NULL)->where('a_office', $userdata['officeid'])->or_where('type', 'all')->order_by('a_id', 'DESC')->get('announcement')->result_array();
            
         }*/
         
          $data = array(
                       "Token"=>$userdata['token']
                      );
          $this->db->where('id', $userdata['userid'])->update('mst_guard',$data);
         
         
        if(count($result) > 0) {
            echo json_encode(array('announcement' => $result));exit;
        } else {
            echo json_encode(array('empty' => 0));exit;
        }
    }
    
    
    
  
 /*===================================================
            Send SMS
 =====================================================*/
    public function sendsms($newmessage,$number)
    {
		$user = "CFAUS";
		$password = "123456";
		$sender_id = "ECFAUS";
		$sender = $number;
		$priority = "ndnd";
		
	  //  $apikey = '704ed302-6523-44b3-b80e-ad4493803cd5';
		
		$sms_type = "normal";
		$message = $newmessage;
		$data = array('user'=>$user,'pass'=>$password,'sender'=>$sender_id,'phone'=>$sender,'text'=>$message,'priority'=>$priority,'stype'=>$sms_type);
		
	   // http://sms.admarksolution.com/sendSMS?username=Swayam2&message=testmsgg&sendername=SWAYAM&smstype=TRANS&numbers=9987671046&apikey=704ed302-6523-44b3-b80e-ad4493803cd5
		$ch = curl_init('http://trans.smsplus.co.in/api/sendmsg.php?');
		
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		
		try
		{     
			$response = curl_exec($ch);
			//echo var_dump($response);
			curl_close($ch);
			//redirect('Login/checkotp/'.$_POST['mobileno']);
			//echo var_dump($response);
			//echo 'Message has been sent.';
			//return 1; 
			

		}
		catch(Exception $e)
		{
			return 0;
			//echo 'Message: ' .$e->getMessage();
		
		}
                
    }
    
    
    public function sendsms2()
    {
		$user = "CFAUS";
		$password = "123456";
		$sender_id = "ECFAUS";
		$sender = "9689850813";
		$priority = "ndnd";

        $newmessage='asdddfdf';
       
	  //  $apikey = '704ed302-6523-44b3-b80e-ad4493803cd5';
		
		$sms_type = "normal";
		$message = $newmessage;
		$data = array('user'=>$user,'pass'=>$password,'sender'=>$sender_id,'phone'=>$sender,'text'=>$message,'priority'=>$priority,'stype'=>$sms_type);
		
	   // http://sms.admarksolution.com/sendSMS?username=Swayam2&message=testmsgg&sendername=SWAYAM&smstype=TRANS&numbers=9987671046&apikey=704ed302-6523-44b3-b80e-ad4493803cd5
		$ch = curl_init('http://trans.smsplus.co.in/api/sendmsg.php?');
		
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		
		try
		{     
			$response = curl_exec($ch);
			//echo var_dump($response);
			curl_close($ch);
			//redirect('Login/checkotp/'.$_POST['mobileno']);
			//echo var_dump($response);
			//echo 'Message has been sent.';
			//return 1; 
			

		}
		catch(Exception $e)
		{
			return 0;
			//echo 'Message: ' .$e->getMessage();
		
		}
                
    }
 
    function notificationTest() 
    {

       	$data = array( 
			'title'     => 'This is a title.',
			'body'      => 'Here is a message.',
			'vibrate'   => 1,
			'sound'      => 1
		);

                 //FCM api URL
        
        // $target = 'cKL1wQ7ovoo:APA91bFfn3j6EeQGZJhl3d5PcBtSlEWxi6cLx0DmVl_vv1MM3Y8iVB2qDsD9QHvDYYpb23PT_ge1kfspaPeufUO69P1I_uEQi8SY3ILnqCgPTCIMcm0ZHvVIb22f4Y8k7FSu9q4f-vRo';
        $target = 'cLUD1YRdld8:APA91bFtSYk4I57iierly5F6ErpcEwEjpEm3hMR7SHE_JwP5lMVdhcGfXxJT_4HF-FjX5aUOYGsj6YwWko3QZkDhS8rMLdfNsE3bzK-d4AZYVVBVFN3NAsC9-Q5j5SobCpPw3lOhXvfz';
        
        $url = 'https://fcm.googleapis.com/fcm/send';
        
        //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
        //$server_key = 'AIzaSyBJ8h6ArfbSonIxW8f40AZvd2mYT6K0LF4';
        $server_key = 'AIzaSyA7FLM4I88RdWg-cFk3GtK8dNRQuYoyiRs';
        
        $fields = array();
        $fields['data'] = $data;
        $fields['to'] = $target;
        
        //header with content_type api key
        $headers = array(
        'Content-Type:application/json',
        'Authorization:key='.$server_key
        );
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        if ($result === FALSE) {
          die('FCM Send Error: ' . curl_error($ch));
        //return 0;
        }
           curl_close($ch);
        //return 1;
        var_dump($result);
	   
	           
	}
	
	/**
	 * Worker Attendance Save
	 * 
	 */
	 
	 public function save_worker_attendance() {
	     $userdata= json_decode(file_get_contents('php://input'), true);
	   //  $todaysChck = $this->db->where('worker_unique_no', $userdata['worker_unique_no'])->where('CURDATE() = DATE(Inserted_DT)')->get('worker_attendance')->num_rows();
    //     if(!empty($todaysChck)) {
    //         echo json_encode(array('exists' => 1));exit;
    //     }
        
	     $checkUser = $this->db->where('unique_id', $userdata['worker_unique_no'])->get('reg__new_docw')->row();
	     if(count($checkUser) > 0) {
	         $data['naka_id'] = $userdata['naka_id'];
	         $data['worker_unique_no'] = $userdata['worker_unique_no'];
	         $data['latitude'] = $userdata['latitude'];
	         $data['longitude'] = $userdata['longitude'];
	         $data['Inserted_SI'] = $userdata['id'];
	         $data['Inserted_BY'] = $userdata['username'];
	         $data['Inserted_DT'] = date('Y-m-d H:i:s');
	         
	         $this->db->insert('worker_attendance', $data);
	         echo json_encode(array('success' => 1));exit;
	     } else {
	         echo json_encode(array('empty' => 0));exit;
	     }
	 }
	
	
	/**
	 * Scheme API
	 * 
	 */
	 
	 public function fetchScheme() {
	    $userdata = json_decode(file_get_contents('php://input'),true);
        $user = $this->db->select('unique_id, pd_fname, pd_mname, pd_lname')->where('unique_id', $userdata['userid'])->where('deleted_dt IS NULL')->get('reg__new_docw')->row();
        
        if(!empty($user)) {
            $data['success'] = 1;
            $data['userid'] = $userdata['userid'];
            $data['user'] = $user;
            $availed = $this->db->join('scheme_master sm', 'sm.id = us.schemes')->where('us.userid', $userdata['userid'])->get('user_schemes us')->result_array();
            $data['schemes_availed'] = $availed;
            
            if(count($availed) > 0) {
                foreach($availed as $avl) {
                    $avaledSchArr[] = $avl['schemes'];
                }    
                $this->db->where_not_in('id', $avaledSchArr);
            }
            $not_availed = $this->db->get('scheme_master')->result_array();
            $data['schemes_not_availed'] = $not_availed;
            $data['scheme_master'] = $this->db->get('scheme_master')->result_array();
        } else {
            $data['empty'] =  0;
            $data['user'] = $user;
            $data['schemes_availed'] = array();
            $data['schemes_not_availed'] = array();
            $data['scheme_master'] = $this->db->get('scheme_master')->result_array();
        }

        
        echo json_encode($data);exit;
	 }
	 
	 public function saveScheme() {
	     $userdata = json_decode(file_get_contents('php://input'),true);
	     $user = $this->db->select('unique_id, pd_fname, pd_mname, pd_lname')->where('unique_id', $userdata['userid'])->where('deleted_dt IS NULL')->get('reg__new_docw')->row();
	     if(!empty($user)) {
                $schmesList =  $userdata['schemeno'];
        
                $userResult = $this->db->where('userid', $userdata['userid'])->get('user_schemes')->result();
                if(count($userResult) > 0 ) {
                    $usrSchemesArr = array();
                    foreach($userResult as $usrScheme) {
                        $usrSchemesArr[] = $usrScheme->schemes;
                    }
                    if(!in_array($schmesList, $usrSchemesArr)) {
                        $data['userid'] = strtoupper($userdata['userid']); 
                        $data['schemes'] = $schmesList; 
                         
                        $data['Inserted_SI'] = $userdata['id']; 
                        $data['Inserted_BY'] = $userdata['username']; 
                        $data['Inserted_DT'] = date('Y-m-d H:i:s'); 
                        
                         $this->db->insert('user_schemes', $data);
                         
                         $availed = $this->db->join('scheme_master sm', 'sm.id = us.schemes')->where('us.userid', $userdata['userid'])->get('user_schemes us')->result_array();
                         echo json_encode(array('success' => 1, 'schemes' => $availed));exit;
                    }
                    
                } else {
                    $data['userid'] = strtoupper($userdata['userid']); 
                    $data['schemes'] = $schmesList; 
                     
                    $data['Inserted_SI'] = $userdata['id']; 
                    $data['Inserted_BY'] = $userdata['username']; 
                    $data['Inserted_DT'] = date('Y-m-d H:i:s'); 
                    
                    $this->db->insert('user_schemes', $data);
                    
                    $availed = $this->db->join('scheme_master sm', 'sm.id = us.schemes')->where('us.userid', $userdata['userid'])->get('user_schemes us')->result_array();
                    echo json_encode(array('success' => 1, 'schemes' => $availed));exit;
                }
                
                echo json_encode(array('empty' => 0));exit; 
	     } else {
	        echo json_encode(array('empty' => 0));exit;    
	     }
         
	 }
	 
	 public function image_upload()
	{
	    
	    $data = json_decode(file_get_contents('php://input'),true);
	    
        $image = $data['image'];
        $name = time();
        $name = $name.rand(100,999);
        $decodedImage = base64_decode($image);
        file_put_contents("uploads/".$name.".jpg", $decodedImage);
        $img = $name.".jpg";
        echo json_encode(array('success'=>1,'image_path'=>$img));
	}
	 
	 
	 //Upload document
	 
    public function upload_document()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        $check = $this->db->where('unique_id',$userdata['regid'])->where('Deleted_DT',NULL)->get('reg__new_docw')->result();
        if(count($check) > 0){
               $data = array(
                   "support_document"=>$userdata['image1'],
                   "support_self_declare"=>$userdata['image2'],
                   "support_aadhar_consent"=>$userdata['image3'],
                   "support_90days_work"=>$userdata['image4']
                  );
            if($this->db->where('unique_id',$userdata['regid'])->update('reg__new_docw',$data)) 
            {
                echo json_encode(array("success"=>1)); 
            }else{
                echo json_encode(array("failed"=>0)); 
            }
        } else {
           echo json_encode(array("notfound"=>0)); 
        }
    }
    
    
    //forgot password
    
    public function forgot_password() {
        $userdata = json_decode(file_get_contents('php://input'),true);
        if(!empty($userdata['username'])) {
            $login = $this->db->where('username', $userdata['username'])->where('Deleted_DT',NULL)->get('mst_guard mg')->row();
            if(!empty($login)) {
                $newmessage = "Your username is: {$login->username} and password: {$login->password}" ;
                $this->sendsms($newmessage, $login->contact);
                echo json_encode(array('success' => 1));exit;
            } else {
                echo json_encode(array('error' => 0));exit;
            }
        }
    }
    
    public function morningmsg()
    {
        $showmsg = $this->db->select('*')->where('deleted_DT', NULL)->get('mst_guard')->result(); 
        
        foreach($showmsg as $disp){
            $msg = 'Good morning.....! how are you';
            $this->insertmsg($msg,$disp->id);
        }
    }
    
    public function afternoonmsg()
    {
        $showmsg = $this->db->select('*')->where('deleted_DT',NULL)->get('mst_guard')->result(); 
        
        foreach($showmsg as $disp){
            $msg = 'Good afternoon.....! how are you';
            $this->insertmsg($msg,$disp->id);
        }
    }
    
    public function eveningmsg()
    {
        $showmsg = $this->db->select('*')->where('deleted_DT',NULL)->get('mst_guard')->result(); 
        
        foreach($showmsg as $disp){
            $msg = 'Good evening...! how are You';
            $this->insertmsg($msg,$disp->id);
        }
    }
    
    public function dinnermsg()
    {
        $showmsg = $this->db->select('*')->where('deleted_DT',NULL)->get('mst_guard')->result(); 
        
        foreach($showmsg as $disp){
            $msg = 'Hi..! how are You';
            $this->insertmsg($msg,$disp->id);
        }
    }

    public function nightmsg()
    {
        $showmsg = $this->db->select('*')->where('deleted_DT',NULL)->get('mst_guard')->result(); 
        
        foreach($showmsg as $disp){
            $msg = 'Good night';
            $this->insertmsg($msg,$disp->id);
        }
    }
    
    public function insertmsg($msg,$id)
    {
        $data = array('complaint_desc'=>$msg,'guard_name'=>$id,'admin_msg'=>1,'inserted_by'=>'admin','inserted_SI'=>1,'inserted_DT'=>date('Y-m-d H:i:s'));
        $this->db->insert('mst_complaint',$data);
    }
    
    
    
    public function getpatienthistory()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        
        if($userdata['userid']!='')
        {
                $rs = $this->db->select('previous_status as status,tbl_previous_status.inserted_dt as insertdate, patient_id')->where('tbl_previous_status.patient_id',$userdata['userid'])->join('mst_guard msg','msg.id=tbl_previous_status.patient_id','left')->where('msg.deleted_DT',NULL)->order_by('tbl_previous_status.pre_id','DESC')->get('tbl_previous_status')->result();
                
                $show = $this->db->select('patient_status as status, inserted_DT as insertdate,id as patient_id')->where('id',$userdata['userid'])->where('deleted_DT',NULL)->get('mst_guard')->row();
                
                $count = $this->db->select('patient_status as status, inserted_DT as insertdate,id as patient_id')->where('id',$userdata['userid'])->where('deleted_DT',NULL)->get('mst_guard')->num_rows();
                
               // echo $count;
                if(count($rs) > 0)
                {
                    foreach($rs as $row)
                    {
                        $refference['patienthistory'][] = $row;
                    }
                    echo json_encode($refference);
                }
                else if($count!=0)
                {
                    $refference['patienthistory'][] = $show;
                    echo json_encode($refference);
                }
                else
                {
                   echo json_encode(array("failed"=>0)); 
                }
        }
        else
        {
            echo json_encode(array("failed"=>0)); 
        }
    }
    
    
    public function updatepatientstatus()
    {
        $show = $this->db->select('*')->where('deleted_DT',NULL)->get('mst_guard')->result();
        
        foreach($show as $info)
        {
            if($info->age!='')
            {
                if($info->age <= 10)
                {
                    $data2 = array('patient_status'=>2);
                    $this->db->where('id',$info->id)->update('mst_guard',$data2);
					
                }
				else if($info->age >= 60)
                {
                    $data2 = array('patient_status'=>2);
                    $this->db->where('id',$info->id)->update('mst_guard',$data2);
					
                }
				else if($info->age > 10 && $info->age < 60)
                {
                    $data = array('patient_status'=>3);
                    $this->db->where('id',$info->id)->update('mst_guard',$data);
					
                }
                
            }
        }
    }
    
    
    			
					    
        /*****************************************************************************************************************
    
             Location insert for map
    
    *********************************************************************************************************************/
    	
    
    
         
    public function insert_location_map()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        	        
        
         
        foreach($userdata['loclist'] as $row)
    	{
    	    
    	    $location = $this->db->where('guard_id', $row['gid'])->where('datetime >  DATE_SUB(NOW(), INTERVAL 5 MINUTE)')->get('guard_location_map')->result();

    	    if(empty($location)) {
    	        
    	    
                 $data = array(
                       "guard_id"=>$row['gid'],
                       "office_id"=>$row['officeid'],
                       "attendance_id"=> $row['aid'],
                       "datetime"=>$row['datetime'],
                       "LAT"=>$row['lat'],
                       "LONGI"=> $row['log'],
                       "area"=> $row['area'],
                       "popup_count"=> $row['pcount'],
                       "inserted_by"=>$row['userid'],
                       "inserted_SI"=>$row['username'],
                       "inserted_DT"=>date('Y-m-d H:i:S')
                      );
                      $return = $this->db->insert('guard_location_map',$data); 
                      
    	    } else{
            	echo json_encode(array("success"=>1)); 
            	exit;
    	    }
                              
    	}              
        if($return) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
        
      
    }
    
       
    
    /*****************************************************************************************************************
    
               Selfi Attendance
    
    *********************************************************************************************************************/
  
	 
	 public function image_upload_selfi()
	{
	    
	    $userdata = json_decode(file_get_contents('php://input'),true);
	    
        $image = $userdata['image'];
        $name = time();
        $name = $name.rand(100,999);
        $decodedImage = base64_decode($image);
        file_put_contents("uploads/".$name.".jpg", $decodedImage);
        $img = $name.".jpg";
           /* $surveyCheck = $this->db->where('Inserted_Si',$userdata['userid'])->where("DATE(Inserted_Dt) = CURDATE()")->get('tbl_selfi_attendance')->result();
            if(empty($surveyCheck)) {*/
                  $data = array(
                       "Pname"=>$userdata['userid'],
                       "Loc_id"=> $userdata['locid'],
                       "Lat"=>$userdata['lat'],
                       "Log"=> $userdata['log'],
                       "Area"=>$userdata['area'],
                       "Image"=>$img,
                       "Inserted_Si"=>$userdata['userid'],
                       "Inserted_By"=>$userdata['username'],
                       "Inserted_Dt"=>date('Y-m-d H:i:S')
                      );
                 if($this->db->insert('tbl_selfi_attendance',$data)) 
                {
                    echo json_encode(array("success"=>1)); 
                }else{
                    echo json_encode(array("failed"=>0)); 
                } 
          /*  } else {
                echo json_encode(array("already_exist"=>0)); 
            }*/
            
	}
	 
    
    
    
    /*****************************************************************************************************************
    
                Push Notification Code
    
    *********************************************************************************************************************/
    	
	
	  public function pushnotification() {
        
               $rs=$this->db->select('Token')->where('Token is NOT NULL')->where('deleted_DT',NULL)->where('status','Active')->get('mst_guard')->result();
        
                     if(count($rs)>0)
                    {
                       // echo 'cursor here ';
                        
                
                     //   echo count($rs);
                        foreach ($rs as $d) {
                          
                          if(!empty($d->Token))
                          {
                             // echo 'inside if';
                            $data = array(
                                "title" => "location",
                                "message" => "test",
                            );
                            
                            $target = $d->Token;
                            
                          //  echo $target.' <br>';
                         
                         //$target = "e8YsaLtBQ3SnPHAE6EYiiD:APA91bGLM_BI7GeVZlLCNPG9HJAUqhhwPW2LzrRb46coAtoQuWnOlQbIaCu-2WxlrJaKBZe3XhPqytHLCkqLpq52UbH_AGZ_zHQw5v-7VR6KEyHhd9vCucBgnkB7glf_p1YG2L-aqMZ-";
                            $url = 'https://fcm.googleapis.com/fcm/send';
                          //  $server_key = 'AIzaSyCN1oi0d9lqmSgbUYsQVCoslv7OrFh8m8g';
                                $server_key = 'AAAA5pN4Y8M:APA91bFMoetTPnVlYyPVQjNTATFPrKi16qFAaFif8zuCMXqe_eMHHLxnlx6tqvr5Q372VMSmbsZ_uQ505dIDU0S6_ptH8T4XtoXz3lDumeVOiAyWedbaWXuDOkVxAxQnQJjd4vsfLpHP';
                            $fields = array
                                    (
                                    'to'    => $target,
                                    'data'  => $data
                                    );
                                
                            
                         /*   $headers = array(
                                'Authorization:key=' . API_ACCESS_KEY,
                                'Content-Type:application/json'
                            );
                            */
                             $headers = array(
                                'Authorization:key=' . $server_key,
                                'Content-Type:application/json'
                            );
                            
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $url);
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
                            $result = curl_exec($ch);
                                // var_dump($result);
                                // die;
                                if ($result === FALSE) {
                                    die('FCM Send Error: ' . curl_error($ch));
                                    return 0;
                                }
                                
                                 curl_close($ch);
                          }
                        }
        }
            
    }
    
    
    	  public function morning_attendance_reminder() {
        
                $rs=$this->db->select('Token,id')->where('Token is NOT NULL')->where('deleted_DT',NULL)->where('status','Active')->get('mst_guard')->result();
               
                //$rs=$this->db->select('msg.Token')->where('msg.Token is NOT NULL')->where('msg.deleted_DT',NULL)->join('tbl_selfi_attendance tbs','tbs.Pname = msg.id','left')->where('DATE(tbs.Inserted_Dt) != CURDATE()')->where('msg.status','Active')->get('mst_guard msg')->result();
                    
                    if(count($rs)>0)
                    {
                       // echo 'cursor here ';
                     //   echo count($rs);
                        foreach ($rs as $d) {
                         
                           $checkattendance = $this->db->where('Inserted_Si',$d->id)->where("DATE(inserted_DT) = CURDATE()")->get('tbl_selfi_attendance')->result();
                          if(empty($checkattendance)) {
                        
                          if(!empty($d->Token))
                          {
                             
                            $data = array(
                                "title" => "Morning Attendance",
                                "message" => "Please upload your morning attendance.",
                            );
                            
                            $target = $d->Token;
                         
                         //$target = "e8YsaLtBQ3SnPHAE6EYiiD:APA91bGLM_BI7GeVZlLCNPG9HJAUqhhwPW2LzrRb46coAtoQuWnOlQbIaCu-2WxlrJaKBZe3XhPqytHLCkqLpq52UbH_AGZ_zHQw5v-7VR6KEyHhd9vCucBgnkB7glf_p1YG2L-aqMZ-";
                            $url = 'https://fcm.googleapis.com/fcm/send';
                          //  $server_key = 'AIzaSyCN1oi0d9lqmSgbUYsQVCoslv7OrFh8m8g';
                                $server_key = 'AAAA5pN4Y8M:APA91bFMoetTPnVlYyPVQjNTATFPrKi16qFAaFif8zuCMXqe_eMHHLxnlx6tqvr5Q372VMSmbsZ_uQ505dIDU0S6_ptH8T4XtoXz3lDumeVOiAyWedbaWXuDOkVxAxQnQJjd4vsfLpHP';
                            $fields = array
                                    (
                                    'to'    => $target,
                                    'data'  => $data
                                    );
                                
                            
                         /*   $headers = array(
                                'Authorization:key=' . API_ACCESS_KEY,
                                'Content-Type:application/json'
                            );
                            */
                             $headers = array(
                                'Authorization:key=' . $server_key,
                                'Content-Type:application/json'
                            );
                            
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $url);
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
                            $result = curl_exec($ch);
                                // var_dump($result);
                                // die;
                                if ($result === FALSE) {
                                    die('FCM Send Error: ' . curl_error($ch));
                                    return 0;
                                }
                                
                                 curl_close($ch);
                          }
                          }
                       
                        }
        }
            
    }
    
     public function evening_attendance_reminder() {
        
               $rs=$this->db->select('Token')->where('Token is NOT NULL')->where('deleted_DT',NULL)->where('status','Active')->get('mst_guard')->result();
        
                     if(count($rs)>0)
                    {
                        
                
                        foreach ($rs as $d) {
                          
                          if(!empty($d->Token))
                          {
                            $data = array(
                                "title" => "Evening Attendance",
                                "message" => "Please upload your evening attendance",
                            );
                            
                            $target = $d->Token;
                         
                            $url = 'https://fcm.googleapis.com/fcm/send';
                                $server_key = 'AAAA5pN4Y8M:APA91bFMoetTPnVlYyPVQjNTATFPrKi16qFAaFif8zuCMXqe_eMHHLxnlx6tqvr5Q372VMSmbsZ_uQ505dIDU0S6_ptH8T4XtoXz3lDumeVOiAyWedbaWXuDOkVxAxQnQJjd4vsfLpHP';
                            $fields = array
                                    (
                                    'to'    => $target,
                                    'data'  => $data
                                    );
                    
                             $headers = array(
                                'Authorization:key=' . $server_key,
                                'Content-Type:application/json'
                            );
                            
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $url);
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
                            $result = curl_exec($ch);
                                // var_dump($result);
                                // die;
                                if ($result === FALSE) {
                                    die('FCM Send Error: ' . curl_error($ch));
                                    return 0;
                                }
                                
                                 curl_close($ch);
                          }
                        }
        }
            
    }
    
    
        
    /*****************************************************************************************************************
    
                Insert Red Spot
    
    *********************************************************************************************************************/
    
    
    public function insert_redspot()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
         
                 $data = array(
                       "Patient_Id"=>$userdata['pid'],
                       "Building_name"=>$userdata['bname'],
                       "Area"=>$userdata['area'],
                       "Lattitude"=>$userdata['lat'],
                       "Longititude"=>$userdata['longt'],
                       "Inserted_By"=>$userdata['userid'],
                       "Inserted_Si"=>$userdata['username'],
                       "Inserted_Dt"=>date('Y-m-d H:i:S')
                      );
        if($this->db->insert('tbl_red_spot',$data)) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
      
    }
    
    
     public function insert_areasealed()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
         
                 $data = array(
                       "patient_id"=>$userdata['pid'],
                       "area_name"=>$userdata['area'],
                       "road_no1"=>$userdata['road1'],
                       "road_no2"=>$userdata['road2'],
                       "Inserted_By"=>$userdata['userid'],
                       "Inserted_Si"=>$userdata['username'],
                       "Inserted_Dt"=>date('Y-m-d H:i:S')
                      );
        if($this->db->insert('tbl_area_sealed',$data)) 
        {
            echo json_encode(array("success"=>1)); 
        }else{
            echo json_encode(array("failed"=>0)); 
        }
      
    }
    
    
    
    public function hospitallist()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        
        $rs = $this->db->select('hos_id,hos_name,type')->where('Deleted_DT',NULL)->where('type',1)->order_by('hos_id','DESC')->get('mst_hospital')->result();
        
        if(count($rs) > 0)
        {
            foreach($rs as $row)
            {
                $refference['hospitallist'][] = $row;
            }
            echo json_encode($refference);
        }else{
            
           echo json_encode(array("empty"=>0)); 
        }
    }
    
     public function facilitylist()
    {
        $userdata = json_decode(file_get_contents('php://input'),true);
        
        $rs = $this->db->select('hos_id,hos_name,type')->where('Deleted_DT',NULL)->order_by('hos_id','DESC')->get('mst_hospital')->result();
        $patientlist = $this->db->select('id,name,age,contact')->where('patient_status','1')->where('deleted_DT',NULL)->order_by('id',"desc")->get('mst_guard')->result();
        if(count($rs) > 0)
        {
            foreach($rs as $row)
            {
                $refference['hospitallist'][] = $row;
            }
          
        }
        
         if(count($patientlist) > 0)
          {
            foreach($patientlist as $row)
            {
                $refference['patientlist'][] = $row;
            }
           
        }
        
        if(count($rs) > 0 || count($patientlist) > 0){
            echo json_encode($refference);  
        }
        else{
            
           echo json_encode(array("empty"=>0)); 
        }
    }
  
  
    
    public function patient_list(){
         $userdata = json_decode(file_get_contents('php://input'),true);
        $patientlist = $this->db->select('id,name,age,contact')->where('Inserted_SI',$userdata['userid'])->where('patient_status','1')->where('deleted_DT',NULL)->order_by('id',"desc")->get('mst_guard')->result();
          if(count($patientlist) > 0)
          {
            foreach($patientlist as $row)
            {
                $patients['patientlist'][] = $row;
            }
            echo json_encode($patients);
        }else{
            
           echo json_encode(array("empty"=>0)); 
        }
    }
    
       public function positive_patient_list(){
         $userdata = json_decode(file_get_contents('php://input'),true);
        $patientlist = $this->db->select('id,name,age,contact')->where('patient_status','1')->where('deleted_DT',NULL)->order_by('id',"desc")->get('mst_guard')->result();
          if(count($patientlist) > 0)
          {
            foreach($patientlist as $row)
            {
                $patients['patientlist'][] = $row;
            }
            echo json_encode($patients);
        }else{
            
           echo json_encode(array("empty"=>0)); 
        }
    }
    
        
    public function patient_app_version(){
         echo json_encode(array("version"=>"1.2")); 
    }
    
    public function dcotor_app_version(){
        echo json_encode(array("version"=>"1.2")); 
    }






    public function update_riskpatient()
    {
        $getpatient = $this->db->select('*')->where('deleted_DT',NULL)->where('type','contact')->get('mst_guard')->result();

        foreach($getpatient as $disp)
        {   
                        $query=$this->db->order_by('risk_id', 'DESC')->limit('1')->get('tbl_patient_risk')->row();
                            @$pqidstring = explode('RSK', $query->risk_uniq);
                            @$pqid = array($pqidstring[1], 1);
                            $pqid = array_sum($pqid);
                            $pqidlength = strlen($pqid);
                            if($pqidlength == 1)
                            {
                              $uniqidd = '000'.$pqid;
                            }
                            else if($pqidlength == 2)
                            {
                              $uniqidd = '00'.$pqid;
                            }
                            else if($pqidlength == 3)
                            {
                              $uniqidd = '0'.$pqid;
                            }
                            else
                            {
                              $uniqidd = $pqid;
                            }
                            $uniq_id='RSK'.$uniqidd;
                      
                    $dataup = array(
                        "risk_uniq_id"=>$uniq_id);
                    $this->db->where('id',$disp->id)->update('mst_guard',$dataup);
            

                    if($disp->type == "contact")
                    {
                        if($disp->risk_type == 1)
                        {
                                   if($disp->gender=='Male')
                                   {
                                          $genderinfo = 1;
                                   } 
                                   else if($disp->gender =='Female')
                                   {
                                         $genderinfo = 2;
                                   }

                                    $positiveinfo = $disp->person_id;

                                    $riskinfo = array('risk_uniq'=>$uniq_id,'patient_id'=>$positiveinfo,'risk_type'=>$disp->risk_type,'inserted_DT'=>date('Y-m-d H:i:s'));
                                    $this->db->insert('tbl_patient_risk',$riskinfo); 

                                    $riskaddmore = array('uniq_id'=>$uniq_id,'patient_id'=>$positiveinfo,'risk_type'=>$disp->risk_type,'memeber_name'=>$disp->name,'age'=>$disp->age,'gender'=>$genderinfo,'mobile_no'=>$disp->contact,'relationship'=>$disp->relationship,'date_of_exposure'=>$disp->date_of_exposure,'date_of_observation'=>$disp->DOB,'symptoms'=>$disp->symptoms,'address'=>$disp->address,'advisal'=>$disp->advised,'advise_location'=>$disp->facility_name,'in_tmc_area'=>$disp->location,'save_staus'=>1,'inserted_DT'=>date('Y-m-d H:i:s'));
                                    $this->db->insert('tbl_risk_addmore',$riskaddmore); 
                        }
                        else 
                        {
                                   if($disp->gender=='Male')
                                   {
                                          $genderinfo = 1;
                                   } 
                                   else if($disp->gender=='Female')
                                   {
                                         $genderinfo = 2;
                                   }
                                    $positiveinfo = 'other';
                                    $riskinfo = array('risk_uniq'=>$uniq_id,'patient_id'=>$positiveinfo,'risk_type'=>$disp->risk_type,'inserted_DT'=>date('Y-m-d H:i:s'));
                                    $this->db->insert('tbl_patient_risk',$riskinfo); 

                                    $riskaddmore = array('uniq_id'=>$uniq_id,'patient_id'=>$positiveinfo,'risk_type'=>$disp->risk_type,'memeber_name'=>$disp->name,'age'=>$disp->age,'gender'=>$genderinfo,'mobile_no'=>$disp->contact,'relationship'=>$disp->relationship,'date_of_exposure'=>$disp->date_of_exposure,'date_of_observation'=>$disp->DOB,'symptoms'=>$disp->symptoms,'address'=>$disp->address,'advisal'=>$disp->advised,'advise_location'=>$disp->facility_name,'in_tmc_area'=>$disp->location,'save_staus'=>1,'inserted_DT'=>date('Y-m-d H:i:s'));
                                    $this->db->insert('tbl_risk_addmore',$riskaddmore);
                        }
                }

        }

}


public function add_history()
    {
        $getpatient = $this->db->select('*')->where('deleted_DT',NULL)->get('mst_guard')->result();

        foreach($getpatient as $disp)
        {   
                $riskinfo = array('patient_id'=>$disp->id,'previous_status'=>$disp->type,'inserted_dt'=>date('Y-m-d H:i:s'));
                $this->db->insert('tbl_previous_status',$riskinfo); 

        }
}



    
    
    // public function transferpatientlist()
    // {
    //     $userdata = json_decode(file_get_contents('php://input'),true);
        
    //     $transferlist =  $this->db->select('mst.id ,mst.name, mst.inserted_SI')->where('msd.transfer_status',NULL)->join('tr_assign_duty msd','mst.id=msd.guard_name')->where('mst.deleted_DT',NULL)->or_where('mst.inserted_SI',$userdata['userid'])->or_where('(mst.deleted_DT IS NOT NULL AND mst.deactive_cronjob_flag = 1)')->order_by('mst.id',"desc")->get('mst_guard mst')->result();
 

    //     if(count($transferlist) > 0)
    //     {
    //         echo json_encode(array("success"=>1,"patientlist"=>$transferlist));
    //     }else{
            
    //       echo json_encode(array("empty"=>0)); 
    //     }
    // }
    
    
    
    
    
    
}