<?php ob_start();
session_start();
ob_end_flush(); // Flush any buffered output
//error_reporting(E_ALL);
ini_set('display_errors', 0);
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {

public $baseURL ;
	public function __construct() 
	{ 
		parent::__construct();
         $this->baseURL = base_url();
		 $this->load->library("pagination");
	}	

  public function index(){
	$data=array();
    $this->load->view('login',$data);	
  }
  public function login(){
	  $data=array();//print_r($_POST);die;
		if ($this->input->server('REQUEST_METHOD') === 'POST'){
	    $email=$this->input->post('email');
	   $password=$this->input->post('password');
        $check=checkLogin($email,$password);
		//print_r($check);die;
        if(count($check) > 0){
		$this->session->set_userdata('user_login', (array)$check);
         $this->session->set_userdata('loggedIn',TRUE);
		 //print_r($this->session->userdata('user_login'));
		 //print_r($this->session->userdata('loggedIn'));
		$msg = "<p class='alert alert-success'>Login Successful</p>";
         $this->session->set_flashdata('msg', $msg);
       // header('location:https://www.dres.in/leadmanagementcrm/home/dashboard');
		redirect('home/dashboard');	
		}else{
		$msg = "<p class='alert alert-danger'>Email Or Password Do Not Match</p>";
         $this->session->set_flashdata('msg', $msg);
          redirect('home');	
		}		
	}  
  }
  
  public function leadreport(){
		$data=array(); 
       $act=activitys();
	  if(!empty($act)){ redirect('home');}
	/*$id=$this->input->post('id');
    $sel="select tllc.*,tll.username from tbl_lead_tl_caller as tllc 
	join tbl_lead_user as tll on tll.id=tllc.cl_id 
	where tllc.tl_id='".$id."'";
    $query = $this->db->query($sel);	
	$studentData = $query->result();*/
	//print_r($_POST);
	
	if ($_POST)
	{ $data['source_id']=$_POST['source_id'];
	 $data['from_date']=$_POST['from_date'];
	 $data['to_date']=$_POST['to_date'];
       $data['filter_data']=$this->session->set_userdata('filter',$_POST);
		$_SESSION['leadsdata']=$data['leads']=leadDistribution($_POST);
		$data['counts']='';
	
	}else{
	$data['source_id']='';
	$data['from_date']='';
	$data['to_date']='';
	$data['filename']='';	
	$data['filter_data']=$this->session->userdata('filter');
    $data['leads']='';
    $data['counts']='';
	}
	
	$this->load->view('leadreport',$data);	  
  }
  
  public function dashboard(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	 // print_r($this->session->userdata('user_login'));
     // print_r($this->session->userdata('loggedIn'));
	 // $this->check_session();	
	$this->load->view('dashboard',$data);	
  }
  
  	public function logout() {
      $this->session->unset_userdata('userdata');
      $this->session->sess_destroy();
        redirect('home');
    }
	 public function users(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();
		 $this->load->library('pagination');
$config['base_url'] = base_url().'home/users';
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$config['total_rows'] =count(getUsersfilter('',$data['filter_data'],$config["per_page"], $page));
$config['per_page'] = 10;
$this->pagination->initialize($config);
	if ($_POST)
	{ 
       $data['filter_data']=$this->session->set_userdata('filter',$_POST);
		$data['leads']=getUsersfilter('',$_POST,$config["per_page"], $page);
		$data['counts']=count(getUsersfilter('',$_POST,$config["per_page"], $page));
		$data["total_count"] = $config["total_rows"];
        $this->session->set_userdata('total_count', $data["total_count"]);
	}else{
	$data['filter_data']=$this->session->userdata('filter');
    $data['leads']=getUsersfilter('',$data['filter_data'],$config["per_page"], $page);
    $data['counts']=count(getUsersfilter('',$data['filter_data'],$config["per_page"], $page));
	if($this->session->userdata('total_count')){
	$data["total_count"] = $this->session->userdata('total_count');
	}
	else{
    $data["total_count"] = $rowcount;
	}
	}
   $data['links']=$this->pagination->create_links();
	$this->load->view('users',$data);	
  }
  	 public function college_list(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();
		 $this->load->library('pagination');
$config['base_url'] = base_url().'home/college_list';
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$config['total_rows'] =count(getProjectsfilter('',$data['filter_data'],$config["per_page"], $page));
$config['per_page'] = 20;
$this->pagination->initialize($config);
	if ($_POST)
	{ 
       $data['filter_data']=$this->session->set_userdata('filter',$_POST);
		$data['leads']=getProjectsfilter('',$_POST,$config["per_page"], $page);
		$data['counts']=count(getProjectsfilter('',$_POST,$config["per_page"], $page));
		$data["total_count"] = $config["total_rows"];
        $this->session->set_userdata('total_count', $data["total_count"]);
	}else{
	$data['filter_data']=$this->session->userdata('filter');
    $data['leads']=getProjectsfilter('',$data['filter_data'],$config["per_page"], $page);
    $data['counts']=count(getProjectsfilter('',$data['filter_data'],$config["per_page"], $page));
	if($this->session->userdata('total_count')){
	$data["total_count"] = $this->session->userdata('total_count');
	}
	else{
    $data["total_count"] = $rowcount;
	}
	}
   $data['links']=$this->pagination->create_links();
	$this->load->view('property_list',$data);	
  }
  
    	 public function course_list(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();
		 $this->load->library('pagination');
$config['base_url'] = base_url().'home/course_list';
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$config['total_rows'] =count(getCoursefilter('',$data['filter_data'],$config["per_page"], $page));
$config['per_page'] = 20;
$this->pagination->initialize($config);
	if ($_POST)
	{ 
       $data['filter_data']=$this->session->set_userdata('filter',$_POST);
		$data['leads']=getCoursefilter('',$_POST,$config["per_page"], $page);
		$data['counts']=count(getCoursefilter('',$_POST,$config["per_page"], $page));
		$data["total_count"] = $config["total_rows"];
        $this->session->set_userdata('total_count', $data["total_count"]);
	}else{
	$data['filter_data']=$this->session->userdata('filter');
    $data['leads']=getCoursefilter('',$data['filter_data'],$config["per_page"], $page);
    $data['counts']=count(getCoursefilter('',$data['filter_data'],$config["per_page"], $page));
	if($this->session->userdata('total_count')){
	$data["total_count"] = $this->session->userdata('total_count');
	}
	else{
    $data["total_count"] = $rowcount;
	}
	}
   $data['links']=$this->pagination->create_links();
	$this->load->view('course_list',$data);	
  }
  
  
  
  	 public function lead_info(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();
		 $this->load->library('pagination');
$config['base_url'] = base_url().'home/lead_info';
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$config['total_rows'] =leadListcount('',$data['filter_data'],$config["per_page"], $page);
$config['per_page'] = 50;
$this->pagination->initialize($config);
	if ($_POST)
	{ 
    $data['filter_data']=$this->session->set_userdata('filter',$_POST);
	$data['leads']=leadList('',$_POST,$config["per_page"], $page);
	$data['counts']=leadListcount('',$_POST,$config["per_page"], $page);
	$data["total_count"] = $config["total_rows"];
    $this->session->set_userdata('total_count', $data["total_count"]);
	}else{
	$data['filter_data']=$this->session->userdata('filter');
    $data['leads']=leadList('',$data['filter_data'],$config["per_page"], $page);
    $data['counts']=leadListcount('',$data['filter_data'],$config["per_page"], $page);
	if($this->session->userdata('total_count')){
	$data["total_count"] = $this->session->userdata('total_count');
	}
	else{
    $data["total_count"] = $rowcount;
	}
	}
   $data['links']=$this->pagination->create_links();
	$this->load->view('lead_info',$data);	
  }
  	 public function my_team(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();
	$userid=$this->session->userdata('user_login');
$caller=getCallerLists($userid[0]['id']);
foreach($caller as $get){
	$ids .=$get->cl_id.',';
}
  $ids = rtrim($ids,',');
		 $this->load->library('pagination');
$config['base_url'] = base_url().'home/my_team';
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$config['total_rows'] =leadListcount('',$data['filter_data'],$config["per_page"], $page,$ids);
$config['per_page'] = 50;
$this->pagination->initialize($config);

	if ($_POST)
	{ 
       $data['filter_data']=$this->session->set_userdata('filter',$_POST);
		$data['leads']=myleadList('',$_POST,$config["per_page"], $page,$ids);
		$data['counts']=leadListcount('',$_POST,$config["per_page"], $page,$ids);
		$data["total_count"] = $config["total_rows"];
        $this->session->set_userdata('total_count', $data["total_count"]);
	}else{
	$data['filter_data']=$this->session->userdata('filter');
    $data['leads']=myleadList('',$data['filter_data'],$config["per_page"], $page,$ids);
    $data['counts']=leadListcount('',$data['filter_data'],$config["per_page"], $page,$ids);
	if($this->session->userdata('total_count')){
	$data["total_count"] = $this->session->userdata('total_count');
	}
	else{
    $data["total_count"] = $rowcount;
	}
	}
   $data['links']=$this->pagination->create_links();
	$this->load->view('my_team',$data);	
  } 
  public function upload_lead(){
	/*unset($_SESSION['set']);
	unset($_SESSION['csv_start_id']);
	unset($_SESSION['csv_last_id']);
	unset($_SESSION['file_name']);
	unset($_SESSION['heading']);*/
	$newValues=array();
	$data=array(); 
     $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();$user=$this->session->userdata('user_login');
	     if ($this->input->server('REQUEST_METHOD') === 'POST')
	{ $file_name = $_FILES['csv']['name']; 
        $valid_formats = array("csv", "CSV");
	$name = $_FILES['csv']['name'];
        $size = $_FILES['csv']['size'];
	$path="./assets/uploads/crm/excel/";
	$final_file_name =date('Y-m-d h:i:g')."-uploaded_by".$user[0]['username']."".$file_name;
	$_SESSION['file_name']=$final_file_name;
	$tmp = $_FILES['csv']['tmp_name'];
	$ad=move_uploaded_file($tmp, $path.$final_file_name);
	$csvFile =  $path.$_SESSION['file_name'];
	$lines = file($csvFile, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
    $num_rows = count($lines);
     foreach ($lines as $line) {
    $csv = str_getcsv($line);
    if (!array_filter($csv)) {
        $num_rows--;
    }
    }
    $file_handle = fopen($csvFile, 'r');
    while(!feof($file_handle)) {
        $line_of_text[] = fgetcsv($file_handle, 20480);
    }//print_r($line_of_text);die;
  $user_id=$user[0]['id'];
  fclose($file_handle);
  $_SESSION['heading']= $data['heading']=$heading= $line_of_text[0];
  $headingarray=getHeadingarray(); $head='';
  foreach($headingarray as $headings){
   $head .=$headings->field.",";
  }
   $head=rtrim($head,',');
 //  print_r($head);
  $newheading=explode(',',$head);
 // print_r($newheading);
   $m = count($newheading); 
    $n = count($data['heading']); 
      if(isSubset($newheading, $data['heading'], $m, $n)){ 
	$string='';  
  $arr=array_slice($line_of_text, 1);
 // print_r($arr);//die;
  $datad= $arr;
  $he=implode('`,`',$heading);
   $string .= "`".$he."`";  
   $last_id = [];$strids='';
  for($i=0;$i<count($datad);$i++){
  // $newValues = preg_replace('/[^a-zA-Z0-9_.\-@ ]/', '', $datad[$i]);
  //$vals = array_map('trim', $newValues);
  // $hes=implode("','",$newValues);
   
   if (is_array($datad[$i])) {
    $newValues = array_map(function($val) {
        return preg_replace('/[^a-zA-Z0-9_.\-@ ]/', '', $val);
    }, $datad[$i]);
    $hes = implode("','", $newValues);
} else {
    $hes = preg_replace('/[^a-zA-Z0-9_.\-@ ]/', '', $datad[$i]);
}
   
  // print_r($hes);die;
  if($hes!=''){
   $insert="INSERT into `tbl_csvimport_helper` (".$string.") values ('".$hes."');";//die;
   $insert=$this->db->query($insert);  
  $last_id[] = $this->db->insert_id(); 
   }

} 
//echo "jgjghj";
//print_r($last_id);
     $_SESSION['csv_start_id']=reset($last_id);
     $_SESSION['csv_last_id']=end($last_id);
	$this->session->set_flashdata('message', '<div class="text-success lead"><strong> Uploaded CSV Successfully!</strong></div>');
	$_SESSION['set']="setBlock";
	//header("Location:https://tenacioushub.com/real-estate-demo/index.php/home/upload_lead");
   redirect('home/upload_lead');
	 } 
    else{ $this->session->set_flashdata('message', '<div class="text-success lead"><strong> Incorrect Excel Format</strong></div>');
	//header("Location:https://tenacioushub.com/real-estate-demo/index.php/home/upload_lead");
	redirect('home/upload_lead'); 
	 } 
	}
	
	 $data['headingarray']=getHeadingarray();
	  foreach($_SESSION['heading'] as $headings){
     $head .=$headings.",";
     }
      $head=rtrim($head,',');
	  $start_id=$_SESSION['csv_start_id'];
      $last_id=$_SESSION['csv_last_id'];
  if($start_id!=''){
    $update ="UPDATE tbl_csvimport_helper set `valid_flg`='DUP' WHERE phone IN( SELECT distinct phone FROM tbl_lead_leads where `phone`!='')  AND `id`  BETWEEN ".$start_id." and ".$last_id."";
    $updat=$this->db->query($update);
    $update_status="update `tbl_csvimport_helper` set `valid_flg` = 'DEL' where `id` IN (select * from (select `id` from `tbl_csvimport_helper` group by `phone` having count(`phone`) > 1) a) AND `id` BETWEEN ".$start_id." and ".$last_id."";
    $updates=$this->db->query($update_status); 
    $update_space="update `tbl_csvimport_helper` set `phone` = REPLACE( trim(TRIM(LEADING '0' FROM `phone`)),' ','') where `id` BETWEEN ".$start_id." and ".$last_id."";
    $updatespace=$this->db->query($update_space);
    $update_space1="update `tbl_csvimport_helper` set `phone` = REPLACE( trim(TRIM(LEADING '91-' FROM `phone`)),' ','') where `id` BETWEEN ".$start_id." and ".$last_id."";
    $updatespace14=$this->db->query($update_space1);
	$update_space14="update `tbl_csvimport_helper` set `phone` = REPLACE( trim(TRIM(LEADING '91' FROM `phone`)),' ','') where `id` BETWEEN ".$start_id." and ".$last_id."";
    $updatespace14=$this->db->query($update_space14);
    $update_space11="update `tbl_csvimport_helper` set `phone` = REPLACE( trim(TRIM(LEADING '(+91)-' FROM `phone`)),' ','') where `id` BETWEEN ".$start_id." and ".$last_id."";
    $updatespace11=$this->db->query($update_space11); 	
	 $update_space112="update `tbl_csvimport_helper` set `phone` = REPLACE( trim(TRIM(LEADING '+91-' FROM `phone`)),' ','') where `id` BETWEEN ".$start_id." and ".$last_id."";
    $updatespace112=$this->db->query($update_space112);
    $add="update `tbl_csvimport_helper` set `added_on` = NOW(),`caller_id`='".$user[0]['id']."' where `id` BETWEEN ".$start_id." and ".$last_id."";
    $adds=$this->db->query($add); 	
	 }
		$data['uploaddata']=getCSVData('',$head.',valid_flg',$_SESSION['csv_start_id'],$_SESSION['csv_last_id']);
		 if($start_id!=''){
		 $sql="select count(id) as `counts` from `tbl_csvimport_helper` WHERE `id`  BETWEEN ".$start_id." and ".$last_id." AND `valid_flg`='DUP'";
	    $student_data=$this->db->query($sql);
		$resultData = $student_data->result(); 
		$data['dupresultdata']=$resultData[0]->counts;
		if(((($resultData[0]->counts)/count($data['uploaddata']))*100) > 50){//echo "hfghgh";die;
		$this->session->set_flashdata('message', '<div class="text-success lead"><strong> Duplicate File Uploaded</strong></div>');
		 $this->reset_all();
		 }
		 $sqlw="delete from `tbl_csvimport_helper` WHERE `id`  BETWEEN ".$start_id." and ".$last_id." AND (`valid_flg`='DUP'  OR `valid_flg`='DEL')";
	   $this->db->query($sqlw);
		}
	
	$this->load->view('upload',$data);	
  }
  
  public function reset_all(){
	$start_id=$_SESSION['csv_start_id'];
    $last_id=$_SESSION['csv_last_id'];
	$delete="delete from tbl_csvimport_helper WHERE `id`  BETWEEN ".$start_id." and ".$last_id." "; 
	$del=$this->db->query($delete);
	unset($_SESSION['set']);
	unset($_SESSION['csv_start_id']);
	unset($_SESSION['csv_last_id']);
	unset($_SESSION['file_name']);
	unset($_SESSION['heading']);	
	unset($_SESSION['left_data']);
	redirect('home/upload_lead');
}
  public function updatesource(){
	  $_SESSION['source_updated']='source_updated';
	  $start_id=$_SESSION['csv_start_id'];
      $last_id=$_SESSION['csv_last_id'];
 $source_id=$_POST['source_id'];
 $college=$_POST['college'];
 $course=$_POST['course'];
 if($_POST['caller_id']!=''){
 $caller_id=$_POST['caller_id'];
 }else{
 $caller_id=1;	 
 }
  $update_space="update `tbl_csvimport_helper` set `college` = '".$college."',`course` = '".$course."',`source_id` = '".$source_id."',`lead_status`='17',`caller_id`='".$caller_id."',`status`='Y' where `id` BETWEEN ".$start_id." and ".$last_id."";
    $updatespace=$this->db->query($update_space); 
	
	$updatepace="UPDATE tbl_csvimport_helper t1 INNER JOIN tbl_lead_city t2 ON t1.city = t2.city_name SET t1.city = t2.id ";
    $updatepaces=$this->db->query($updatepace);	
	$updatepace="UPDATE tbl_csvimport_helper set city='1' where city REGEXP '^[a-zA-Z]+$' ";
    $updatepaces=$this->db->query($updatepace);	
	redirect('home/upload_lead');
  }
  public function uploadlead(){
	 if ($this->input->server('REQUEST_METHOD') === 'POST')
	{
 $data=array(); 
     $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();
	if($_SESSION['source_updated']==''){
	$this->session->set_flashdata('message', '<div class="text-danger lead"><strong> Source Not updated</strong></div>');
	redirect('home/upload_lead');	
	}
	$user_id=$this->session->userdata('user_login');
 $start_id=$_SESSION['csv_start_id'];
 $last_id=$_SESSION['csv_last_id'];
 $fields = $this->db->field_data('tbl_lead_leads'); 
  foreach($fields as $colname){
	 if($colname->name=='id'){$cols.= "";}else{
	 $cols.= "`".$colname->name."`,"; }
 }
 $cols = rtrim($cols,',');
  $insert="INSERT INTO tbl_lead_leads (".$cols.") SELECT ".$cols." FROM tbl_csvimport_helper WHERE `id`  BETWEEN ".$start_id." and ".$last_id." AND (`valid_flg`='' OR `valid_flg`='DUP') ORDER BY id ASC ";
 $query=$this->db->query($insert);
 $rows=$this->db->affected_rows();
 $first=$this->db->insert_id();
 $last=$first+($rows-1);
 $file=$_SESSION['file_name'];
	if($insert){
	$delete="delete from tbl_csvimport_helper WHERE `id`  BETWEEN ".$start_id." and ".$last_id." "; 
	$del=$this->db->query($delete);
	unset($_SESSION['set']);
	unset($_SESSION['csv_start_id']);
	unset($_SESSION['csv_last_id']);
	unset($_SESSION['file_name']);
	unset($_SESSION['heading']);
	$this->session->set_flashdata('message', '<div class="text-success lead"><strong> Upload Lead Successfully!</strong></div>');
	//header("Location:https://tenacioushub.com/real-estate-demo/index.php/home/upload_lead");
	redirect('home/upload_lead');
 } 
}  
  }
  
  public function deleteuser($id=''){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	  $this->check_session();  
  if($id!=''){
	$delete="update tbl_lead_user set `status`='N' where `id`='".$id."'";  
	$query1  = $this->db->query($delete);
	$msg = "<p class='alert alert-success'>User Deleted</p>";
         $this->session->set_flashdata('msg', $msg);
	//header("Location:https://tenacioushub.com/real-estate-demo/index.php/home/users");	 
	redirect('home/users');
  }
  }
  
  public function reset(){
	$data=array(); 
       $act=activitys();
	  if(!empty($act)){ redirect('home');}
	  $this->check_session();
     $this->session->unset_userdata('filter');
	unset($_SESSION['set']);
	unset($_SESSION['csv_start_id']);
	unset($_SESSION['csv_last_id']);
	unset($_SESSION['file_name']);
	unset($_SESSION['heading']);
	unset($_SESSION['leadsdata']);
	unset($_SESSION['from_date']);
	unset($_SESSION['to_date']);
     $e=$_SERVER['HTTP_REFERER'];
	 redirect($e);
  }
  
  public function updateuser(){
	$id=$this->input->post('id');
	$username=$this->input->post('username');
	$email=$this->input->post('email');
	$phone=$this->input->post('phone');
	$usertype=$this->input->post('usertype');
	$status=$this->input->post('status');
	$tl=$this->input->post('tl');
	$password=$this->input->post('password');
	$lead_sharing_type=implode(',',$this->input->post('lead_sharing_type'));
	
	if($id!=''){
	 $update="update tbl_lead_user set `username`='".$username."',`email`='".$email."',`phone`='".$phone."',`lead_sharing_type`='".$lead_sharing_type."',`user_type`='".$usertype."',`status`='".$status."' ,`password`='".$password."'  where `id`='".$id."'";
	$query = $this->db->query($update);
	$laststatus_id = $this->db->insert_id();
   if($tl!=''){
	 $del="delete from tbl_lead_tl_caller where `cl_id`='".$id."'"; 
     $query11  = $this->db->query($del);	 
	 $sql1="insert tbl_lead_tl_caller set `tl_id`='".$tl."',`cl_id`='".$id."',`added_on`=NOW()"; 
	$query1  = $this->db->query($sql1);
   }
	}
  }
  
   public function updatecourse(){
	$id=$this->input->post('id');
	$name=$this->input->post('name');
	$stream=$this->input->post('stream');
	$status=$this->input->post('status');
	
	if($id!=''){
	 $update="update tbl_lead_course set `name`='".$name."',`stream`='".$stream."',`status`='".$status."'  where `id`='".$id."'";
	$query = $this->db->query($update);
	$laststatus_id = $this->db->insert_id();
 	}
  }
  
     public function updatecollege(){
	$id=$this->input->post('id');
	$name=$this->input->post('name');
	$city=$this->input->post('city');
	$city1=explode('-',$city);
	$status=$this->input->post('status');
	if($id!=''){
	 $update="update tbl_lead_college set `name`='".$name."',`city`='".$city1[0]."',`state`='".$city1[1]."',`status`='".$status."'  where `id`='".$id."'";
	$query = $this->db->query($update);
	$laststatus_id = $this->db->insert_id();
 	}
  }
  
  
   public function updatelead(){
	$id=$this->input->post('id');
	$username=$this->input->post('username');
	$email=$this->input->post('email');
	$phone=$this->input->post('phone');
	$college=$this->input->post('college');
	$course=$this->input->post('course');
	$followup=$this->input->post('followup');
	if(($this->input->post('status')==5) || ($this->input->post('status')==14)){
	$sitedate=$this->input->post('followup');
    $set=',`site_visit_date`="'.$followup.'"';	
	}else{$set='';}
	$status=$this->input->post('status');
	$remark=" || ".$this->input->post('remark');
	if($id!=''){
	$update="update tbl_lead_leads set `name`='".$username."',`email`='".$email."',`phone`='".$phone."',`college`='".$college."',`course`='".$course."',`followup_date`='".$followup."',`lead_status`='".$status."',`recent_update`=NOW(),`feedback`=CONCAT(feedback, '".$remark."') ".$set." where `id`='".$id."'";
	$query = $this->db->query($update);
	}
  }
  
  public function getCallerList(){
	$id=$this->input->post('id');
	$userid=$this->session->userdata('user_login');
    $sel="select tllc.*,tll.username from tbl_lead_tl_caller as tllc 
	join tbl_lead_user as tll on tll.id=tllc.cl_id 
	where tllc.tl_id='".$id."'";
    $query = $this->db->query($sel);	
	$studentData = $query->result();
if($userid[0]['user_type']==2){
$uurl= base_url()."home/my_team";
} else{ $uurl=base_url()."home/lead_info"; }
echo '<table class="table table-striped b-t b-light">
        <thead><tr>
<td>Caller Name</td>
<td>Total Leads</td>
<td>Follow Up</td>
<td>Interested</td>
<td>Site Visit</td>
</tr></thead>';
	foreach($studentData as $data){
	echo '<tr>
	<td>'.$data->username.'</td>
	<td><form method="post" action="'.$uurl.'"><input type="hidden" name="caller_id" value="'.$data->cl_id.'"/>'.getTotal($data->cl_id).'	<button name="submit" type="submit" style="border: 0px;background: none;font-size: 14px;color: #000;"><i class="fa fa-long-arrow-right"></i></button></form></td>
	<td><form method="post" action="'.$uurl.'"><input type="hidden" name="caller_id" value="'.$data->cl_id.'"/><input type="hidden" name="lad_status" value="3"/>'.getTotal($data->cl_id,3).'	<button name="submit" type="submit" style="border: 0px;background: none;font-size: 14px;color: #000;"><i class="fa fa-long-arrow-right"></i></button></form></td>
	<td><form method="post" action="'.$uurl.'"><input type="hidden" name="caller_id" value="'.$data->cl_id.'"/><input type="hidden" name="lad_status" value="4"/>'.getTotal($data->cl_id,4).'	<button name="submit" type="submit" style="border: 0px;background: none;font-size: 14px;color: #000;"><i class="fa fa-long-arrow-right"></i></button></form></td>
	<td><form method="post" action="'.$uurl.'"><input type="hidden" name="caller_id" value="'.$data->cl_id.'"/><input type="hidden" name="lad_status" value="5"/>'.getTotal($data->cl_id,5).'	<button name="submit" type="submit" style="border: 0px;background: none;font-size: 14px;color: #000;"><i class="fa fa-long-arrow-right"></i></button></form></td>
	</tr>';
	}
	echo '</table>';
    echo '<br/><a href="'.base_url().'home/callerreport/'.$id.'" class="btn btn-primary">Download</a>';
  }

public function callerreport($id=''){
	$sel="select tllc.*,tll.username from tbl_lead_tl_caller as tllc 
	join tbl_lead_user as tll on tll.id=tllc.cl_id 
	where tllc.tl_id='".$id."'";
    $query = $this->db->query($sel);	
	$studentData = $query->result();
	
    $delimiter = ",";
    $filename = "members_" . date('Y-m-d') . ".csv";
    $f = fopen('php://memory', 'w');
    $array='';
    $fields = array('ID','TEAM LEADER','CALLER','TOTAL','NEW','FOLLOWUP','INTERESTED','SITE VISIT','NOT REACHABLE','NOT INTERESTED','CLOSED');
    fputcsv($f, $fields, $delimiter);
    $i=0;
	foreach($studentData as $data){
	    $lineData = array($i+1,GetCounsellorName($id),$data->username,getTotal($data->cl_id),getTotal($data->cl_id,1),getTotal($data->cl_id,3),getTotal($data->cl_id,4),getTotal($data->cl_id,5),getTotal($data->cl_id,11),getTotal($data->cl_id,13),getTotal($data->cl_id,7));
        fputcsv($f, $lineData, $delimiter);
    $i++;}
    
    //move back to beginning of file
    fseek($f, 0);
    
    //set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');
    
    //output all remaining data on a file pointer
    fpassthru($f);

exit;
}
  public function updatemoreinfo(){
	$id=$this->input->post('id');   
	$dob=$this->input->post('dob');  
	$interestedin=$this->input->post('interestedin');  
	$city=$this->input->post('city');  
	$lookingfor=$this->input->post('lookingfor');  
	$whatsapp_no=$this->input->post('whatsapp_no');  
	$site_visit_date=$this->input->post('site_visit_date');  
	$feedback=$this->input->post('feedback'); 
if($id!=''){
	$update="update tbl_lead_leads set `dob`='".$dob."',`city`='".$city."',`looking_for`='".$lookingfor."',`whatsapp_no`='".$whatsapp_no."',`site_visit_date`='".$site_visit_date."',`recent_update`=NOW(),`feedback`='".$feedback."',`interested_in`='".$interestedin."' where `id`='".$id."'";
	$query = $this->db->query($update);
	}	
  }
	public function check_session()
	{   $data=array(); 
          $act=activitys();
	  if(!empty($act)){ redirect('home');}
	   // $this->check_session();
      	//print_r($this->session->userdata('loggedIn'));//die;
		if ($this->session->userdata('loggedIn')!=1) {
				redirect('home');
			}
	}
	public function add_users(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();	
	if ($this->input->server('REQUEST_METHOD') === 'POST'){
	$username=$this->input->post('username');	
	$email=$this->input->post('email');	
	$phone=$this->input->post('phone');	
	$password=$this->input->post('password');	
	$confirm_password=$this->input->post('confirm_password');	
	$user_type=$this->input->post('user_type');	
	$lead_sharing_type='';	
	$tl=$this->input->post('tl');
	$status=$this->input->post('status');
	$date=date('Y-m-d h:i:g');
   $sql="insert tbl_lead_user set `username`='".$username."',`email`='".$email."',`phone`='".$phone."',`password`='".$password."',`lead_sharing_type`='".$lead_sharing_type."',`user_type`='".$user_type."',`status`='".$status."',`added_on`='".$date."'";  
   $query  = $this->db->query($sql);	
   $laststatus_id = $this->db->insert_id();
   if($tl!=''){
	$sql1="insert tbl_lead_tl_caller set `tl_id`='".$tl."',`cl_id`='".$laststatus_id."',`added_on`='".$date."'"; 
	$query1  = $this->db->query($sql1);
   }
   		$msg = "<p class='alert alert-success'>User Added</p>";
         $this->session->set_flashdata('msg', $msg);
		//header('location:https://tenacioushub.com/real-estate-demo/index.php/home/add_users');
         redirect('home/add_users');	
	}
	$this->load->view('add_user',$data);	
	}

	public function add_college(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();	
	if ($this->input->server('REQUEST_METHOD') === 'POST'){
	$name=$this->input->post('name');	
	$leadshare=$this->input->post('leadshare');	
	$city=$this->input->post('city');
$city1=explode('-',$city);	

	$status=$this->input->post('status');
	$date=date('Y-m-d h:i:g');
	$id=$this->session->userdata('user_login');
	$select="select id from tbl_lead_college where (`name`='".$name."' AND `city`='".$city1[0]."') AND `status`='Active'";
	$query = $this->db->query($select);	
	$nums   = $query->num_rows();
	if($nums==0){
   $sql="insert tbl_lead_college set `name`='".$name."',`city`='".$city1[0]."',`state`='".$city1[1]."',`leadshare`='".$leadshare."',`status`='".$status."',`added_on`='".$date."'";  
   $query  = $this->db->query($sql);	
  
   		$msg = "<p class='alert alert-success'>College Added</p>";
         $this->session->set_flashdata('msg', $msg);
		 	// header('location:https://tenacioushub.com/real-estate-demo/index.php/home/add_property');
          redirect('home/add_college');	
	}else{
	  		$msg = "<p class='alert alert-danger'>Propety Already Exists</p>";
         $this->session->set_flashdata('msg', $msg);
		 	// header('location:https://tenacioushub.com/real-estate-demo/index.php/home/add_property');
          redirect('home/add_college');	
	}
	}
	$this->load->view('add_property',$data);	
		
}
	
	public function add_course(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();	
	if ($this->input->server('REQUEST_METHOD') === 'POST'){
	$name=$this->input->post('name');	
	$stream=$this->input->post('stream');	
	
	$status=$this->input->post('status');
	$date=date('Y-m-d h:i:g');
	$id=$this->session->userdata('user_login');
	$select="select id from tbl_lead_course where (`name`='".$name."' AND `stream`='".$stream."') AND `status`='Active'";
	$query = $this->db->query($select);	
	$nums   = $query->num_rows();
	if($nums==0){
   $sql="insert tbl_lead_course set `name`='".$name."',`stream`='".$stream."',`status`='".$status."',`added_on`='".$date."'";  
   $query  = $this->db->query($sql);	
  
   		$msg = "<p class='alert alert-success'>Course Added</p>";
         $this->session->set_flashdata('msg', $msg);
		 	// header('location:https://tenacioushub.com/real-estate-demo/index.php/home/add_property');
          redirect('home/add_course');	
	}else{
	  		$msg = "<p class='alert alert-danger'>Propety Already Exists</p>";
         $this->session->set_flashdata('msg', $msg);
		 	// header('location:https://tenacioushub.com/real-estate-demo/index.php/home/add_property');
          redirect('home/add_course');	
	}
	}
	$this->load->view('add_course',$data);	
		
}	
	
	
	public function add_lead(){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();	
	$id=$this->session->userdata('user_login');
	if ($this->input->server('REQUEST_METHOD') === 'POST'){
	$name=$this->input->post('name');	
	$email=$this->input->post('email');	
	$phone=$this->input->post('phone');	
	if($this->input->post('whatsapp_no')!=''){	
		$whatsapp_no=$this->input->post('whatsapp_no');	
	}else{
		$whatsapp_no=$this->input->post('phone');	
	}
	$lead_status=$this->input->post('lead_status');
	$source_id=$this->input->post('source_id');
	$looking_for=$this->input->post('looking_for');
	$interested_in=$this->input->post('interested_in');
	$course=$this->input->post('course');
	$college=$this->input->post('college');
	$feedback=$this->input->post('feedback');
	if($this->input->post('caller_id')!=''){
	$caller_id=$this->input->post('caller_id');
	}else{
	$caller_id=$id[0]['id'];	
	}
	$date=date('Y-m-d h:i:g');
	$select="select id from tbl_lead_leads where (`phone`='".$phone."') AND `status`='Y'";
	$query = $this->db->query($select);	
	$nums   = $query->num_rows();
	if($nums==0){
   $sql="insert tbl_lead_leads set `name`='".$name."',`email`='".$email."',`phone`='".$phone."',`whatsapp_no`='".$whatsapp_no."',`lead_status`='".$lead_status."',`source_id`='".$source_id."',`looking_for`='".$looking_for."',`interested_in`='".$interested_in."',`feedback`='".$feedback."',`caller_id`='".$caller_id."',`added_on`='".$date."',`status`='Y',`college`='".$college."',`course`='".$course."'";  
   $query  = $this->db->query($sql);	
   $laststatus_id = $this->db->insert_id();
   if($tl!=''){
	$sql1="insert tbl_lead_tl_caller set `tl_id`='".$tl."',`cl_id`='".$laststatus_id."',`added_on`='".$date."'"; 
	$query1  = $this->db->query($sql1);
   }
   		$msg = "<p class='alert alert-success'>Lead Added</p>";
         $this->session->set_flashdata('msg', $msg);
		 	// header('location:https://tenacioushub.com/real-estate-demo/index.php/home/add_lead');
          redirect('home/add_lead');	
	}else{
	  		$msg = "<p class='alert alert-danger'>Lead Already Exists</p>";
         $this->session->set_flashdata('msg', $msg);
		 	// header('location:https://tenacioushub.com/real-estate-demo/index.php/home/add_lead');
         redirect('home/add_lead');	
	}
	}
	$this->load->view('add_lead',$data);	
		
}

public function InfoEdit(){
	$id=$this->input->post('id');
	$getdata=leadListt($id);//print_r($getdata);
	if($getdata[0]->whatsapp_no!=0){$whatsapp=$getdata[0]->whatsapp_no;}else{$whatsapp=$getdata[0]->phone;}
	$data='';
	$data .='<div id="myModal" class="modal fade in" role="dialog">
							  <div class="modal-dialog ppup-bx" style="width:90%;">
								<div class="modal-content" style="padding:2% 0">								
                                 <h3 style="padding:1% 3%;">'.$getdata[0]->name.'--'.$getdata[0]->source.'</h3>';
								$data .='<div class="form-group ">
								    	<div class="col-lg-3">
											<label for="Username" class="control-label col-lg-12">Interested In</label>
											 <input class=" form-control" id="interestedin'.$id.'" name="interested_in" type="text" value="'.$getdata[0]->interested_in.'" >
                                      ';									
								
                                        $data .='</div>
										
								    	<div class="col-lg-3">
											<label for="Username" class="control-label col-lg-12">DOB</label>
											 <input class=" form-control" id="dob'.$id.'" name="dob" type="date" value="'.$getdata[0]->dob.'" ></div>
                                      
										<div class="col-lg-3">
											<label for="Username" class="control-label col-lg-12">City</label>
                                        <select class="form-control" name="city" id="city'.$id.'" required="">
											<option value="">Select City</option>';
										foreach(getCity() as $get){
											
											$data .='<option' ;
											if($get->id==$getdata[0]->city){$sell='selected';}else{$sell='';} 
											$data .=' '.$sell.' value="'.$get->id.'">'.$get->city_name.'</option>';
										}
											$data .='</select>
                                        </div>
										<div class="col-lg-3">
											<label for="Username" class="control-label col-lg-12">Looking For</label>
                                       <input class=" form-control" id="lookingfor'.$id.'" name="lookingfor" type="text" value="'.$getdata[0]->looking_for.'" >
                                       
                                        </div>
										<div class="col-lg-3">
											<label for="Username" class="control-label col-lg-12">Whatsapp No.</label>
                                       <input class=" form-control" id="whatsapp_no'.$id.'" name="whatsapp_no" type="text" value="'.$whatsapp.'" maxlength="10" pattern="[0-9]+" onkeypress="return numbersonly(this, event)">
                                       
                                        </div>
										<div class="col-lg-3">
											<label for="Username" class="control-label col-lg-12">Lead Date</label>
                                       <input class=" form-control" readonly="true" id="added_on" name="added_on" type="text" value="'.$getdata[0]->added_on.'" maxlength="10" pattern="[0-9]+" onkeypress="return numbersonly(this, event)">
                                       
                                        </div>
										<div class="col-lg-3">
											<label for="Username" class="control-label col-lg-12">Form Fill Date</label>
                                         <div class="input-group date datetimepicker1" >
											<input type="text" class="form-control ctrl"  id="site_visit_date'.$id.'" name="site_visit_date" value="'.$getdata[0]->site_visit_date.'"/>
											<span class="input-group-addon">
												<span class="glyphicon glyphicon-calendar"></span>
											</span>
										</div>
                                        </div>
                                        <div class="col-lg-3">
										 <label for="Username" class="control-label col-lg-12">Remark</label>
                                       
                                            <textarea class="form-control " id="feedback'.$id.'" name="feedback">'.$getdata[0]->feedback.'</textarea>
                                        </div>
										<div class="col-lg-3">
										 <label for="Username" class="control-label col-lg-12">Share Lead Status</label>
                                       
                                            <textarea class="form-control " >'.$getdata[0]->lead_share_apistatus.'</textarea>
                                        </div>
										';
							
								  $data .='<div class="clearfix"></div><div class="modal-footer modl-fotr">
									<input type="button" id="update" class="btn btn-primary" onclick="update_student_info('.$id.')" value="Update" />
								    <button type="button" class="btn btn-default" id="closeblock" data-dismiss="modal">Close</button>
								  </div>
								 </form>
								</div>
							  </div>
							</div>';
               
          echo $data;
}

public function Communication(){
    $id=$this->input->post('id');
	$getdata=leadList($id);
	$data='';
	$data .='<div id="myModals" class="modal fade in" role="dialog">
							  <div class="modal-dialog ppup-bx" style="width:90%;">
								<div class="modal-content" style="padding:2%">								
                                 <h3 style="padding:1% 3%;">Communication  '.$getdata[0]->name.'--'.$getdata[0]->source.'</h3>';
									$data .='<form method="" action="">
									<p id="showmsg_'.$id.'"></p><br/><br/>
									<div class="col-md-6"><select class="form-control" 
									onchange="getTemplate('.$id.',this)">
									<option value="">Select Template</option>
									<option value="Introduction">Introduction</option>
									<option value="Site Visit">Site Visit</option>
									<option value="Thank You">Thank You</option>
									</select></div>
									<div class="col-md-6"><textarea class="form-control" style="padding:0 2%" rows="8" id="getsmsinbox_'.$id.'" placeholder="Enter Text For SMS"></textarea></div>
									</form>';				
								  $data .='<div class="clearfix"></div><div class="modal-footer modl-fotr">
									<input type="button" id="update" class="btn btn-primary" onclick="update_sent('.$id.','.$getdata[0]->phone.')" value="Send" />
								    <button type="button" class="btn btn-default" id="closeblock" data-dismiss="modal">Close</button>
								  </div>
								 </form>
								</div>
							  </div>
							</div>';
               
          echo $data;	
}
public function leadshare(){
 $id=$this->input->post('id');
 $function=$this->input->post('function');
	$getdata=leadList($id);
	$student_data = $function($id);
	
}

public function Shareleadswithclg(){
 $college_od =$this->input->post('college_od');
	 $leads =$this->input->post('leads');
	 $lead=implode(',',$leads);
		$user=$this->session->userdata('user_login');
		$date=date('Y-m-d h:i:g');
		$clg_detail=getCollegestat($college_od);
		//print_r($clg_detail);
		$function=$clg_detail[0]->leadshare;
		for($i=0;$i<count($leads);$i++){
		$student_data = $function($leads[$i]);
		}	
		if($student_data){
			echo '{ "status" : "1" , "message" : "Lead assigned successfully" }';
             }
           else{
            echo '{ "status" : "0" , "message" : "no data update." }';
               }
}

public function dupleadswithclg(){
$college_od =$this->input->post('college_od');
	 $leads =$this->input->post('leads');
	 $lead=implode(',',$leads);
		$user=$this->session->userdata('user_login');
		$date=date('Y-m-d h:i:g');
		for($i=0;$i<count($leads);$i++){
		$getdata=leadList($leads[$i]);
		 $sql="insert tbl_lead_leads set `name`='".$getdata[0]->name."',`email`='".$getdata[0]->email."',`phone`='".$getdata[0]->phone."',`whatsapp_no`='".$getdata[0]->whatsapp_no."',`lead_status`='17',`source_id`='".$getdata[0]->source_id."',`looking_for`='".$getdata[0]->looking_for."',`interested_in`='".$getdata[0]->interested_in."',`feedback`='',`caller_id`='1',`added_on`=NOW(),`status`='Y',`college`='".$college_od."',`course`='".$getdata[0]->course."',`city`='".$getdata[0]->city."',`dob`='".$getdata[0]->dob."'";  
   $query  = $this->db->query($sql);	
		}
if($query){
			echo '{ "status" : "1" , "message" : "Lead assigned successfully" }';
             }
           else{
            echo '{ "status" : "0" , "message" : "no data update." }';
               }		
}

public function backtrack(){
 $id=$this->input->post('id');
	$getdata=leadList($id);
	$student_data = getStuBackTrackerData($id);
	$data='';
	$data .='<div id="myModalsw" class="modal fade in" role="dialog">
							  <div class="modal-dialog ppup-bx" style="width:90%;">
								<div class="modal-content" style="padding:2% 0">								
                                 <h3 style="padding:1% 3%;">Back Log '.$getdata[0]->name.'--'.$getdata[0]->source.'</h3>
									<div  class="p-row" id="StuBackTracker" style="height:350px;overflow:scroll">';
									if(count($student_data) > 0 ){
									  $data .='
									  <div id="flip-scroll">
									  <table class="table table-bordered">
									  <thead>
										<tr class="warning">
											<th>Date & Time</th>
											<th>Name</th>
											<th>Phone</th>
											<th>Email</th>
											<th>Lead status</th>
											<th>Follow Up</th>
											<th>Site Visit Date</th>
											<th>Counsellor</th>
											<th class="feedback">Remark</th>
										
										</tr>
										</thead>
		
									  <tbody>';
									
										foreach($student_data as $stuData){
									    if($stuData!=''){
										$statusname=getStatus($stuData->lead_status);	
										$data .='<tr>
											<td class="info">'.date('d M Y', strtotime($stuData->change_date)).'&nbsp; <strong> '.date('G:i', strtotime($stuData->change_date)).'</strong></td>
											<td>'.$stuData->name.'</td>
											<td>'.$stuData->phone.'</td>
											<td>'.$stuData->email.'</td>
											<td>'.$statusname[0]->status.'</td>
											<td>'.$stuData->followup_date.'</td>
											<td>'.$stuData->site_visit_date.'</td>
											<td>'.GetCounsellorName($stuData->caller_id).'</td>
											<td class="feedback">'.$stuData->feedback.'</td>
											
										 </tr>';
										} 
								      }
									 $data .='</tbody></table></div>';
									} else{
										$data .='
										<div class="container"><div class="jumbotron text-center">
										  <h2><strong>No Activity log</strong> Found</h2>
										</div></div>';
									}  
								$data .='</div>';				
								  $data .='<div class="clearfix"></div><div class="modal-footer modl-fotr">
									<button type="button" class="btn btn-default" id="closeblock" data-dismiss="modal">Close</button>
								  </div>
								 </form>
								</div>
							  </div>
							</div>';
               
          echo $data;		
}

    public function generate_log()
	{	$this->check_session();
	  $postargs = $this->input->post(NULL,TRUE);	
       $postargs['student_id'];	  
	   if($postargs['operation']!=''){
		 $operation=$postargs['operation']; 
	   }
	   if($postargs['student_id']!=''){
	  $student_id=$postargs['student_id']; 
	   }
	   $date=date('Y-m-d h:i:g');
	   generate_table_log($student_id,$postargs['operation'],'tbl_lead_leads_log',$operation,$date,'tbl_lead_leads');
	   
	}
 public function AssignLeadsCounsellor(){
	 $counsellor =$this->input->post('counsellor');
	 $leads =$this->input->post('leads');
	 $lead=implode(',',$leads);
		$user=$this->session->userdata('user_login');
		$date=date('Y-m-d h:i:g');
		$caller_detail=getCallers($counsellor);
		//print_r($caller_detail);
		for($i=0;$i<count($leads);$i++){
		generate_table_log($leads[$i],'new assign','tbl_lead_leads_log','new assign',$date,'tbl_lead_leads');
		}
		  $sql="UPDATE `tbl_lead_leads` SET `caller_id`='$counsellor',`parent_caller_id`='".$user[0]['id']."',`assigned_lead_time`='$date'  WHERE `id` IN ($lead)";
		 $student_data=$this->db->query($sql);
		 $sql1="UPDATE `tbl_lead_leads` SET `lead_status`='1'  WHERE `id` IN ($lead) AND `lead_status` IN (13,15,8)";
		 $student_data1=$this->db->query($sql1);
		 	//  $apikey = "KJ2lQ7TaJ0GUQfWUIesyPQ";
   //$apisender = "TENHUB";
  // $msg ="".$caller_detail[0]['username']." ".count($leads)." leads assigned to you.Check CRM";
  // $len=strlen($msg);
  // $count=ceil($len/160);
   $num = $caller_detail[0]['phone'];   // MULTIPLE NUMBER VARIABLE PUT HERE...!                 
  // $ms = rawurlencode($msg);   //This for encode your message content    
//file_get_contents("http://api.msg91.com/api/v2/sendsms?authkey=306347A6ZTnEq0Ralm5de374d3&mobiles=".$num."&message=".$msg."&sender=".$apisender."&route=4&country=91");  
 // $url = 'https://www.smsgatewayhub.com/api/mt/SendSMS?APIKey='.$apikey.'&senderid='.$apisender.'&channel=2&DCS=0&flashsms=0&number='.$num.'&text='.$ms.'&route=13';
/* $ch=curl_init($url);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch,CURLOPT_POST,1);
 curl_setopt($ch,CURLOPT_POSTFIELDS,"");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,2);
 $data = curl_exec($ch);*/
 
        $key = "EsBittZOzfIOWk7k";	
		$mbl=$phone; 
		$msg="You have been assigned ".count($leads)." leads. Kindly review your dashboard.-Edifice Reality";
		$message_content=urlencode($msg);
     $count=ceil($msg/160);
		$senderid="EDFREL";	$route= 1;
		$tempid="1707171714989951256";
		$url = "https://manage.txly.in/vb/apikey.php?apikey=".$key."&senderid=".$senderid."&templateid=".$tempid."&number=".$num."&message=".$message_content."";
					
		$output = file_get_contents($url);	/*default function for push any url*/	
 
 
 $update="update tbl_lead_sms set `sms`=sms-".$count."";
 $student_data=$this->db->query($update);
		if($student_data){
			echo '{ "status" : "1" , "message" : "Lead assigned successfully" }';
             }
           else{
            echo '{ "status" : "0" , "message" : "no data update." }';
               }
 }
 
  public function AssignLeadsStatus(){
	 $counsellor =$this->input->post('counsellor');
	 $leads =$this->input->post('leads');
	 $lead=implode(',',$leads);
		$user=$this->session->userdata('user_login');
		$date=date('Y-m-d h:i:g');
		$caller_detail=getCallers($counsellor);
		//print_r($caller_detail);
		for($i=0;$i<count($leads);$i++){
		generate_table_log($leads[$i],'Lead status Change','tbl_lead_leads_log','new assign',$date,'tbl_lead_leads');
		}
		  $sql="UPDATE `tbl_lead_leads` SET `lead_status`='$counsellor',`assigned_lead_time`='$date'  WHERE `id` IN ($lead)";
		 $student_data=$this->db->query($sql);
		 $sql1="UPDATE `tbl_lead_leads` SET `lead_status`='$counsellor'  WHERE `id` IN ($lead) AND `lead_status` IN (13,15,8)";
		 $student_data1=$this->db->query($sql1);
		
		if($student_data){
			echo '{ "status" : "1" , "message" : "Lead assigned successfully" }';
             }
           else{
            echo '{ "status" : "0" , "message" : "no data update." }';
               }
 }
 
 
 public function verifyvisit(){
	 $leads =$this->input->post('leads');
	 $lead=implode(',',$leads);
		$user=$this->session->userdata('user_login');
		$date=date('Y-m-d h:i:g');
		 $sql="UPDATE `tbl_lead_leads` SET `site_visit_verify`='Y',`recent_update`='$date' WHERE `id` IN ($lead)";
		 $student_data=$this->db->query($sql);
		if($student_data){
			echo '{ "status" : "1" , "message" : "Site visit verifies successfully" }';
             }
           else{
            echo '{ "status" : "0" , "message" : "no data update." }';
               }
 }

 	 public function report($csv=''){
	$data=array(); 
      $act=activitys();
	  if(!empty($act)){ redirect('home');}
	$this->check_session();
	if($csv!=''){
	$delimiter = ",";
    $data['filename']=$filename = "reports_" . date('Y-m-d') . ".csv";
    $f = fopen('php://memory', 'w');
    $array='';
    $fields = array('ID','NAME','PHONE','EMAIL','LOOKING FOR','LEAD STATUS','SOURCE','FEEDBACK','ADDED ON','FOLLOW UP','INTERESTED IN','CALLER','SITE VISIT DATE','SITE VISIT VERIFY');
    fputcsv($f, $fields, $delimiter);
    $i=0;
	foreach($_SESSION['leadsdata'] as $datas){
		$leadstatus=getStatus($datas->lead_status);
		$project=getProjects($datas->interested_in);
	    $lineData = array($i+1,$datas->name,$datas->phone,$datas->email,$datas->looking_for,$leadstatus[0]->status,$datas->source,$datas->feedback,$datas->added_on,$datas->followup_date,$project[0]->property_name.'|'.$project[0]->area,$datas->username,$datas->site_visit_date,$datas->site_visit_verify);
        fputcsv($f, $lineData, $delimiter);
    $i++;}
    
    //move back to beginning of file
    fseek($f, 0);
    
    //set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');
    
    //output all remaining data on a file pointer
    fpassthru($f);
    exit;
	}
	if ($_POST)
	{ 
       $data['filter_data']=$this->session->set_userdata('filter',$_POST);
		$_SESSION['leadsdata']=$data['leads']=leadList('',$_POST);
		$data['counts']=leadListcount('',$_POST);
	
	}else{
	$data['filename']='';	
	$data['filter_data']=$this->session->userdata('filter');
    $data['leads']='';
    $data['counts']='';
	}	
	$this->load->view('report',$data);	
  }
 
public function getTemplate(){
  $id=$this->input->post('id');
  $template=$this->input->post('template');
  $smstemp='';	
 $get=getTemplates($template);
 $stu=leadList($id);
 $project=getProjects($stu[0]->interested_in);
 $smstemp=str_replace('[USER]',$stu[0]->name,$get);
 $smstemp=str_replace('[CALLER]',$stu[0]->username,$smstemp);
 $smstemp=str_replace('[DATE]',$stu[0]->site_visit_date,$smstemp);
 $smstemp=str_replace('[PROPERTY]',$project[0]->proprty_name,$smstemp);
 $smstemp=str_replace('[CALLERNUM]',$stu[0]->phones,$smstemp);
 echo $smstemp;
 }
 
 public function sendSMS(){
	 $id=$this->input->post('id');
	 $msg=$this->input->post('msg');
	 $phone=$this->input->post('phone');
	//  $apikey = "KJ2lQ7TaJ0GUQfWUIesyPQ";
   //$apisender = "TENHUB";
   $msg =$msg;
   $len=strlen($msg);
   $count=ceil($len/160);
   $num = $phone;  
    //$msg=str_replace(' ','+',$msg);// MULTIPLE NUMBER VARIABLE PUT HERE...!                 
  // $ms = rawurlencode($msg);   //This for encode your message content                 		
// $url = 'https://www.smsgatewayhub.com/api/mt/SendSMS?APIKey='.$apikey.'&senderid='.$apisender.'&channel=2&DCS=0&flashsms=0&number='.$num.'&text='.$ms.'&route=1';
// file_get_contents("http://api.msg91.com/api/v2/sendsms?authkey=306347A6ZTnEq0Ralm5de374d3&mobiles=".$num."&message=".$msg."&sender=".$apisender."&route=4&country=91"); 
//file_get_contents("http://104.155.222.89/API/WebSMS/Http/v1.0a/index.php?username=tenacious&password=88ee2d-94975&sender=TENHUB&to=".$num."&message=".$msg."&reqid=1&format={json|text}");	 
  
 $key = "EsBittZOzfIOWk7k";	
		$mbl=$phone; 
		//$msg="Enquiry on Landing Page Name ".$property[0]." are Mr/Mrs. ".$name." and Mobile ".$phone."- Edifice";
		$message_content=urlencode($msg);

		$senderid="EDFREL";	$route= 1;
		$url = "https://manage.txly.in/vb/apikey.php?apikey=".$key."&senderid=".$senderid."&templateid=".$tempid."&number=".$phone."&message=".$message_content."";
					
		$output = file_get_contents($url);	/*default function for push any url*/	
   
 /*$ch=curl_init($url);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch,CURLOPT_POST,1);
 curl_setopt($ch,CURLOPT_POSTFIELDS,"");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,2);
 $data = curl_exec($ch);*/
 $update="update tbl_lead_sms set `sms`=sms-".$count."";
 $student_data=$this->db->query($update);
 echo  "<span class='alert alert-success'>SMS Sent</span>";
 }
 
 public function deleteCounsellor(){
	 $leads =$this->input->post('leads');
	 $lead=implode(',',$leads);
		$user=$this->session->userdata('user_login');
		$date=date('Y-m-d h:i:g');
		  $sql="delete from `tbl_lead_user` WHERE `id` IN ($lead)";
		 $student_data=$this->db->query($sql);
		if($student_data){
			echo '{ "status" : "1" , "message" : "Lead Deleted successfully" }';
             }
           else{
            echo '{ "status" : "0" , "message" : "no data update." }';
               }	 
 }
 
 public function deleteProperty(){
 $leads =$this->input->post('leads');
	 $lead=implode(',',$leads);
		$user=$this->session->userdata('user_login');
		$date=date('Y-m-d h:i:g');
		  $sql="delete from `tbl_lead_property` WHERE `id` IN ($lead)";
		 $student_data=$this->db->query($sql);
		if($student_data){
			echo '{ "status" : "1" , "message" : "property Deleted successfully" }';
             }
           else{
            echo '{ "status" : "0" , "message" : "no data update." }';
               }	 
 }
}
?>
