<?php
/**
 
 * User: Muhammed Asif */
/**
 * Description of dBase
 *
 * @author AA
 */
date_default_timezone_set("Asia/Dubai");
class dBase
{



	public $con;
	private $server;
	private $user;
	private $pass;
	private $db;
	private $msgType;
	private $msgText;

   // public $result;


// 	function __construct($server = "127.0.0.1", $user = "root", $pass = "", $db = "indus_lms",$con="")
	function __construct($server = "199.250.207.93", $user = "indusoffice_lms", $pass = "]fX-*gXzD)3P", $db = "indusoffice_lms" ,$con="")
	{
		$this->server = $server;
		$this->user = $user;
		$this->pass = $pass;
		$this->db = $db;
		$this->con = mysqli_connect($this->server, $this->user, $this->pass);


	}

	public function execute($query)
	{
		$this->open();

		$result= mysqli_query($this->con, $query) or die(" " . mysqli_error($this->con));
		$this->close();
		return $result;

	}

	public function open()
	{
		$this->con = mysqli_connect($this->server, $this->user, $this->pass);
		if (!$this->con) {
			$this->msgText = 'Not connected : ' . mysqli_error($this->con);
			$this->msgType = "Error";

		}

		$db_selected = mysqli_select_db($this->con, $this->db);
		if (!$db_selected) {
			$this->msgText = 'Can\'t use database : ' . mysqli_error($this->con);
			$this->msgType = "Error";
		}
	}

	public function getNextId($table, $id)
	{
		$this->open();
		$query = "select ifnull(MAX(id),0) from " . $table;
		$result = mysqli_query($this->con, $query);
		if ($result != "") {
			while ($row = mysqli_fetch_array ($result)) {
				$id = $row[0];
			}
		}
		$this->close();
		return $id + 1;
	}

	public function close()
	{
		$this->con = mysqli_connect($this->server, $this->user, $this->pass);
		mysqli_close($this->con);

	}

	public function Count($query)
	{
		$this->open();
		$sql = mysqli_num_rows($query);

		$this->close();
		return $sql;
	}

	public function CountQuery($CountQuery)
	{
		$CountQuery_q=$this->execute($CountQuery);
		$sql = mysqli_num_rows($CountQuery_q);        
		return $sql;
	}



    //insert into user_course

	public function insert($postedarray,$table)
	{
		$this->open();
		$columns = '';
		$data = '';
        //$postedarray['creation_date']=  date("Y/m/d");
		foreach ($postedarray as $key => $val) {
			if ($key != 'mod' && $key != 'submit' && $key != 'id' && $key != 'awas_btn_add') {

				$columns .= ',' . $key;
				$data .= ',' ."'" . mysqli_real_escape_string($this->con,$val) . "'";
			}
		}

		$primary_get=mysqli_fetch_array($this->execute("SHOW INDEX FROM " .$table. " where `Key_name` = 'PRIMARY'"));
		$primary_name=$primary_get['Column_name'];

		$primary_id  = $this->getNextId($table, $primary_name);

		$query = "INSERT INTO " .$table. " ($primary_name $columns) VALUES($primary_id  $data)";


		$this->execute($query);

		if (@mysqli_error($this->con) == "") {
			$this->setMsgType("Success");
			$this->setMsgText("Inserted successfully");
		} else {
			$this->setMsgType("Error");
			$this->setMsgText("could not Inserted !");
		}
		$this->close();
		return $primary_id;

	}


	public function execute_return_id($query)
	{
		$this->open();
		$result= mysqli_query($this->con, $query) or die(" " . mysqli_error($this->con));
		return mysqli_insert_id($this->con);         
		$this->close();
	}


	public function update($postedarray,$table, $unique_id)
	{

		$this->open();
		foreach ($postedarray as $key => $val) {
			if ($key != 'mod' && $key != 'submit' && $key != 'id' && $key != 'awas_btn_add' ) {
				$columns[] = $key;
				$data[] = mysqli_real_escape_string($this->con,$val);
			}
		}



		$queryvalue = '';

		for ($i = 0; $i < count($columns); $i++) {

			if ($i == 0) {
				$queryvalue = "$columns[$i]='$data[$i]'";
			} else {

				$queryvalue .= "," . "$columns[$i]='$data[$i]'";
			}
		}
		$primary_get=mysqli_fetch_array($this->execute("SHOW INDEX FROM " .$table. " where `Key_name` = 'PRIMARY'"));
		$primary_name=$primary_get['Column_name'];


		$query = "UPDATE  ".$table." SET  " . $queryvalue . "  WHERE  ".$primary_name." = '" . $unique_id . "';";

		$this->execute($query);
		if (@mysqli_error($this->con) == "") {
			$this->setMsgType("Success");
			$this->setMsgText(" updated successfully");
		} else {
			$this->setMsgType("Error");
			$this->setMsgText(" could not update !");
		}
		$this->close();

	}



	public function getMsgType()
	{
		return $this->msgType;
	}

	public function setMsgType($msgType)
	{
		$this->msgType = $msgType;
	}

	public function getMsgText()
	{
		return $this->msgText;
	}

	public function setMsgText($msgText)
	{
		$this->msgText = $msgText;
	}




	function getUserIP()
	{
		$client  = @$_SERVER['HTTP_CLIENT_IP'];
		$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
		$remote  = $_SERVER['REMOTE_ADDR'];

		if(filter_var($client, FILTER_VALIDATE_IP))
		{
			$ip = $client;
		}
		elseif(filter_var($forward, FILTER_VALIDATE_IP))
		{
			$ip = $forward;
		}
		else
		{
			$ip = $remote;
		}

		return $ip;
	}

	function runQuery($query) {
		$this->open();

        // $result= mysqli_query($this->con, $query) or die(" " . mysqli_error($this->con));

		$result = mysqli_query($this->con,$query)or die(" " . mysqli_error($this->con));
		while($row=mysqli_fetch_assoc($result)) {
			$resultset[] = $row;
		}      
		if(!empty($resultset))
			return $resultset;
	}


	function getany_val($getany_val_v1,$getany_val_v2,$getany_val_v3,$getany_val_v4)
	{
		$getany_val_f=$this->queryto_fetch("SELECT `$getany_val_v1` FROM `$getany_val_v2` WHERE `$getany_val_v3`='$getany_val_v4' ");
		return $getany_val_f[$getany_val_v1];
	}




	function queryToWhile($queryToWhile_v1)
	{
		$queryToWhile_r=$this->execute($queryToWhile_v1);
		while($queryToWhile_f[]=mysqli_fetch_array($queryToWhile_r)){}
			return $queryToWhile_f;
	}

	function queryToWhile_2($query)
	{
		$e=$this->execute($query);
		while($f[]=mysqli_fetch_assoc($e)){}
			return $f;
	}

	function queryto_fetch($queryto_fetch_v1)
	{
		$queryto_fetch_r=$this->execute($queryto_fetch_v1);
		$queryto_fetch_f=mysqli_fetch_array($queryto_fetch_r);
		return array_filter($queryto_fetch_f);
	}

	function queryto_fetch_assoc($queryto_fetch_v1)
	{
		$queryto_fetch_r=$this->execute($queryto_fetch_v1);
		$queryto_fetch_f=mysqli_fetch_assoc($queryto_fetch_r);
		return array_filter($queryto_fetch_f);
	}

	

	function queryto_fetch_api($queryto_fetch_v1)
	{
		$queryto_fetch_r=$this->execute($queryto_fetch_v1);
		$queryto_fetch_f=mysqli_fetch_array($queryto_fetch_r);
		return $queryto_fetch_f;
	}



	function createSlug_db($slug) {
		$lettersNumbersSpacesHyphens = '/[^\-\s\pN\pL]+/u';
		$spacesDuplicateHypens = '/[\-\s]+/';

		$slug = preg_replace($lettersNumbersSpacesHyphens, '', $slug);
		$slug = preg_replace($spacesDuplicateHypens, '-', $slug);

		$slug = trim($slug, '-');

		return mb_strtolower($slug, 'UTF-8');
	}



	function response_code($response_code_v1){
		$response_d=$this->queryto_fetch("SELECT `title`,`description`,`expiry`,`followup`,`type`,`status` FROM `response_list` WHERE `code`='$response_code_v1' ");
		return array(    
			'h' => $response_d['title'],
			'c' => $response_d['description'],
			'x' => $response_d['expiry'],
			't' => $response_d['type'],
			'f' => $response_d['followup']
		);
	}


	function dateDiffer($dateDiffer_v1,$dateDiffer_v2){
		$then = new DateTime($dateDiffer_v1);
		$now = new DateTime($dateDiffer_v2);
		$sinceThen = $then->diff($now);
		return array(    
			'y' => $sinceThen->y,
			'm' => $sinceThen->m,
			'd' => $sinceThen->d,
			'h' => $sinceThen->h,
			'i' => $sinceThen->i); 
	}






	function pushNotification($type,$action,$from,$to,$ref,$comment,$title){
		$this->popNotification($type,$action,$from,$to,$ref);
		$dateNoti=date("Y-m-d H:i");
		$this->execute("INSERT INTO `notification`(`not_to`, `not_from`, `type`, `action`, `reference`, `message`,title, `status`, `sent`, `modified`)VALUES('$to','$from','$type','$action','$ref','$comment','$title',0,0,'$dateNoti') ");
		return TRUE;
	}
	function popNotification($type,$action,$from,$to,$ref){
		$this->execute("DELETE FROM `notification` WHERE `type`='$type' AND `not_to`='$to' AND `not_from`='$from' AND `reference`='$ref' AND `action`='$action' ");
	}


    function getEmailBody_assign($em_name,$lead_name,$lead_phone,$r_link,$l_link){
        // <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>New Lead Notification </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/></head><body style="margin:0; padding:0;" bgcolor="#999"> <table style="min-width:320px;" width="100%" cellspacing="0" cellpadding="0" bgcolor="#eaeced"> <table width="600" align="center" cellpadding="0" cellspacing="0"> <tr> <td style="padding:0px 20px;background-color: #fff;"> <table width="100%" cellpadding="0" cellspacing="0"> <tr> <th width="600" align="left" style="font:bold 25px/35px Arial, Helvetica, sans-serif; color:#222;padding-top:25px;"> New Lead Notification </th> </tr><tr> <th width="600" align="left" style="font: 14px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:3px;letter-spacing: 2.3px"> &copy; Lead Management System </th> <th width="10" style="padding:0;"></th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:20px;">Hi '.$em_name.', You have a new lead, Please login to the Lead Management System and review the lead. Please take an action now.</th> <th width="10" style="padding:0;"></th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:20px;padding-bottom: 5px;">Name :'.$lead_name.'</th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;">Phone : '.$lead_phone.'</th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:20px;">Click on the Quick Response button if you are attending the lead now and willing to update later. Click on the Details button to Access LMS </th> <th width="10" style="padding:0;"></th> </tr><tr> <td style="padding:30px 0 10px;"> <table align="left" style="margin:0 auto;" cellpadding="0" cellspacing="0"> <tr> <td data-size="size button" data-min="10" data-max="16" align="center" style=""> <table> <tr style="padding:30px 0 40px;"> <td width="140" style="font:16px/14px Arial, Helvetica, sans-serif; color:#f8f9fb; mso-padding-alt:12px 10px 10px; border-radius:2px;text-align:center; " bgcolor="#259356"><a target="_blank" style="text-decoration:none; color:#fff; display:block; padding:12px 10px 10px;" href="'.$r_link.'">Quick Respond</a></td><td></td><td width="140" style="font:16px/14px Arial, Helvetica, sans-serif; color:#f8f9fb; mso-padding-alt:12px 10px 10px; border-radius:2px;text-align:center; " bgcolor="#fe9316"><a target="_blank" style="text-decoration:none; color:#fff; display:block; padding:12px 10px 10px;" href="'.$l_link.'">Details</a></td></tr></table> </td></tr></table> </td></tr><tr> <th width="600" align="left" style="border-bottom:1px solid #eee;font: 12px/17px Arial, Helvetica, sans-serif; color:#222;padding-top:5px;"></th> </tr><tr> <td style="font:12px/16px Arial, Helvetica, sans-serif; color:#333; padding:20px 0px 0px;">Indus Real Estate LLC &copy; All Rights Reserved. </td></tr><tr> <td style="font:11px/16px Arial, Helvetica, sans-serif; color:#797c82; padding:10px 0px;"> You are receiving this email because you are a part of Indus Real Estate and setup to receive email notification. </td></tr></table> </td></tr></table></table></body></html>
		return $body='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>New Lead Notification </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/></head><body style="margin:0; padding:0;" bgcolor="#999"> <table style="min-width:320px;" width="100%" cellspacing="0" cellpadding="0" bgcolor="#eaeced"> <table width="600" align="center" cellpadding="0" cellspacing="0"> <tr> <td style="padding:0px 20px;background-color: #fff;"> <table width="100%" cellpadding="0" cellspacing="0"> <tr> <th width="600" align="left" style="font:bold 25px/35px Arial, Helvetica, sans-serif; color:#222;padding-top:25px;"> New Lead Notification </th> </tr><tr> <th width="600" align="left" style="font: 14px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:3px;letter-spacing: 2.3px"> &copy; Lead Management System </th> <th width="10" style="padding:0;"></th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:20px;">Hi '.$em_name.', You have a new lead, Please login to the Lead Management System and review the lead. Please take an action now.</th> <th width="10" style="padding:0;"></th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:20px;">Click on the Quick Response button if you are attending the lead now and willing to update later. Click on the Details button to Access LMS </th> <th width="10" style="padding:0;"></th> </tr><tr> <td style="padding:30px 0 10px;"> <table align="left" style="margin:0 auto;" cellpadding="0" cellspacing="0"> <tr> <td data-size="size button" data-min="10" data-max="16" align="center" style=""> <table> <tr style="padding:30px 0 40px;"> <td width="140" style="font:16px/14px Arial, Helvetica, sans-serif; color:#f8f9fb; mso-padding-alt:12px 10px 10px; border-radius:2px;text-align:center; " bgcolor="#259356"><a target="_blank" style="text-decoration:none; color:#fff; display:block; padding:12px 10px 10px;" href="'.$r_link.'">Quick Respond</a></td><td></td><td width="140" style="font:16px/14px Arial, Helvetica, sans-serif; color:#f8f9fb; mso-padding-alt:12px 10px 10px; border-radius:2px;text-align:center; " bgcolor="#fe9316"><a target="_blank" style="text-decoration:none; color:#fff; display:block; padding:12px 10px 10px;" href="'.$l_link.'">Details</a></td></tr></table> </td></tr></table> </td></tr><tr> <th width="600" align="left" style="border-bottom:1px solid #eee;font: 12px/17px Arial, Helvetica, sans-serif; color:#222;padding-top:5px;"></th> </tr><tr> <td style="font:12px/16px Arial, Helvetica, sans-serif; color:#333; padding:20px 0px 0px;">Indus Real Estate LLC &copy; All Rights Reserved. </td></tr><tr> <td style="font:11px/16px Arial, Helvetica, sans-serif; color:#797c82; padding:10px 0px;"> You are receiving this email because you are a part of Indus Real Estate and setup to receive email notification. </td></tr></table> </td></tr></table></table></body></html>';		
	}
	
		
	function getEmailBody_bulk($em_name,$table,$count){
		return $body='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"xmlns:o="urn:schemas-microsoft-com:office:office"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"> <!-- So that mobile will display zoomed in --><meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- enable media queries for windows phone 8 --><meta name="format-detection" content="date=no"> <!-- disable auto date linking in iOS 7-9 --><meta name="format-detection" content="telephone=no"> <!-- disable auto telephone linking in iOS 7-9 --><title>New Lead | LMS &copy; Indus Real Estate LLC </title><style type="text/css">body {margin: 0;padding: 0;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;}table {border-spacing: 0;}table td {border-collapse: collapse;}.ExternalClass {width: 100%;}.ExternalClass,.ExternalClass p,.ExternalClass span,.ExternalClass font,.ExternalClass td,.ExternalClass div {line-height: 100%;}.ReadMsgBody {width: 100%;background-color: #ebebeb;}table {mso-table-lspace: 0pt;mso-table-rspace: 0pt;}img {-ms-interpolation-mode: bicubic;}.yshortcuts a {border-bottom: none !important;}@media screen and (max-width: 599px) {.force-row,.container {width: 100% !important;max-width: 100% !important;}}@media screen and (max-width: 400px) {.container-padding {padding-left: 12px !important;padding-right: 12px !important;}}.ios-footer a {color: #aaaaaa !important;text-decoration: underline;}a[href^="x-apple-data-detectors:"],a[x-apple-data-detectors] {color: inherit !important;text-decoration: none !important;font-size: inherit !important;font-family: inherit !important;font-weight: inherit !important;line-height: inherit !important;}.jean td{text-align: left; border-top:1px solid #3a4893;padding:5px 8px;font-family: arial;font-size:12px; }.jean th{text-align: left; padding:5px;font-family: arial;background-color: #3a4893;color:#fff; }.jean{margin-bottom: 10px;padding:5px 2px;}.button{ padding:8px 15px;border:0;outline: 0;margin:3px;display: inline-block;background-color: #3a4893;color:#fff;font-size: 17px;cursor: pointer;border-radius: 2px;text-transform: uppercase; }</style></head><body style="margin:0; padding:0;" bgcolor="#F0F0F0" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><!-- 100% background wrapper (grey background) --><table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0" bgcolor="#F0F0F0"><tr><td align="center" valign="top" bgcolor="#F0F0F0" style="background-color: #F0F0F0;"><br><!-- 600px container (white background) --><table border="0" width="600" cellpadding="0" cellspacing="0" class="container" style="width:600px;max-width:600px"><tr style="background-color: #fff;" ><td class="container-padding header" align="left" style="padding:15px;font-family:Helvetica, Arial, sans-serif;font-size:24px;font-weight:bold;padding-bottom:12px;color:#3a4893;padding-left:24px;padding-right:24px">Lead Management System</td></tr><tr><td class="container-padding content" align="left" style="padding-left:24px;padding-right:24px;padding-top:12px;padding-bottom:12px;background-color:#ffffff"><div class="title" style="font-family:Helvetica, Arial, sans-serif;font-size:18px;font-weight:600;color:#374550">'.$count.' Leads</div><br><div class="body-text" style="font-family:Helvetica, Arial, sans-serif;font-size:14px;line-height:20px;text-align:left;color:#333333">Hi '.$em_name.', You have '.$count.' new lead, Login to Lead Management System and review the lead. Please take an action now.<br><br><a href="https://indus-inhouse.com/v20/ag/access/#/agent/inbox?status=una" target="SELF" class="button">All Leads </a></div></td></tr><tr><td align="center" valign="top" bgcolor="#F0F0F0" style="background-color: #fff;"><table border="0" width="300" cellpadding="0" cellspacing="0" class="container jean" style="width:600px;max-width:600px"><tr><th>Name</th><th>Source</th><th>Phone</th></tr>'.$table.'</table></td></tr><tr><td class="container-padding footer-text" align="left" style="font-family:Helvetica, Arial, sans-serif;font-size:12px;line-height:16px;color:#aaaaaa;padding-left:24px;padding-right:24px"><br><br>Lead Management System © 2020 Indus Real Estate LLC.<br><br>You are receiving this email because you are a part of Indus Real Estate and setup to receive email notification. <br><br><strong> Indus Real Estate LLC..</strong><br><a href="https://www.indus-inhouse.com" style="color:#aaaaaa">Lead Management System</a><br><br><br></td></tr></table><!--/600px container --></td></tr></table><!--/100% background wrapper--></body></html>';
		
	}

    
	function getEmailBody_bulk_no_leads($em_name,$count){
		return $body='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"xmlns:o="urn:schemas-microsoft-com:office:office"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"> <!-- So that mobile will display zoomed in --><meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- enable media queries for windows phone 8 --><meta name="format-detection" content="date=no"> <!-- disable auto date linking in iOS 7-9 --><meta name="format-detection" content="telephone=no"> <!-- disable auto telephone linking in iOS 7-9 --><title>New Lead | LMS &copy; Indus Real Estate LLC </title><style type="text/css">body {margin: 0;padding: 0;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;}table {border-spacing: 0;}table td {border-collapse: collapse;}.ExternalClass {width: 100%;}.ExternalClass,.ExternalClass p,.ExternalClass span,.ExternalClass font,.ExternalClass td,.ExternalClass div {line-height: 100%;}.ReadMsgBody {width: 100%;background-color: #ebebeb;}table {mso-table-lspace: 0pt;mso-table-rspace: 0pt;}img {-ms-interpolation-mode: bicubic;}.yshortcuts a {border-bottom: none !important;}@media screen and (max-width: 599px) {.force-row,.container {width: 100% !important;max-width: 100% !important;}}@media screen and (max-width: 400px) {.container-padding {padding-left: 12px !important;padding-right: 12px !important;}}.ios-footer a {color: #aaaaaa !important;text-decoration: underline;}a[href^="x-apple-data-detectors:"],a[x-apple-data-detectors] {color: inherit !important;text-decoration: none !important;font-size: inherit !important;font-family: inherit !important;font-weight: inherit !important;line-height: inherit !important;}.jean td{text-align: left; border-top:1px solid #3a4893;padding:5px 8px;font-family: arial;font-size:12px; }.jean th{text-align: left; padding:5px;font-family: arial;background-color: #3a4893;color:#fff; }.jean{margin-bottom: 10px;padding:5px 2px;}.button{ padding:8px 15px;border:0;outline: 0;margin:3px;display: inline-block;background-color: #3a4893;color:#fff;font-size: 17px;cursor: pointer;border-radius: 2px;text-transform: uppercase; }</style></head><body style="margin:0; padding:0;" bgcolor="#F0F0F0" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><!-- 100% background wrapper (grey background) --><table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0" bgcolor="#F0F0F0"><tr><td align="center" valign="top" bgcolor="#F0F0F0" style="background-color: #F0F0F0;"><br><!-- 600px container (white background) --><table border="0" width="600" cellpadding="0" cellspacing="0" class="container" style="width:600px;max-width:600px"><tr style="background-color: #fff;" ><td class="container-padding header" align="left" style="padding:15px;font-family:Helvetica, Arial, sans-serif;font-size:24px;font-weight:bold;padding-bottom:12px;color:#3a4893;padding-left:24px;padding-right:24px">Lead Management System</td></tr><tr><td class="container-padding content" align="left" style="padding-left:24px;padding-right:24px;padding-top:12px;padding-bottom:12px;background-color:#ffffff"><div class="title" style="font-family:Helvetica, Arial, sans-serif;font-size:18px;font-weight:600;color:#374550">'.$count.' Leads</div><br><div class="body-text" style="font-family:Helvetica, Arial, sans-serif;font-size:14px;line-height:20px;text-align:left;color:#333333">Hi '.$em_name.', You have '.$count.' new lead, Login to Lead Management System and review the lead. Please take an action now.<br><br><a href="https://indus-inhouse.com/v20/ag/access/#/agent/inbox?status=una" target="SELF" class="button">All Leads </a></div></td></tr><tr><td align="center" valign="top" bgcolor="#F0F0F0" style="background-color: #fff;"><table border="0" width="300" cellpadding="0" cellspacing="0" class="container jean" style="width:600px;max-width:600px"></table></td></tr><tr><td class="container-padding footer-text" align="left" style="font-family:Helvetica, Arial, sans-serif;font-size:12px;line-height:16px;color:#aaaaaa;padding-left:24px;padding-right:24px"><br><br>Lead Management System © 2020 Indus Real Estate LLC.<br><br>You are receiving this email because you are a part of Indus Real Estate and setup to receive email notification. <br><br><strong> Indus Real Estate LLC..</strong><br><a href="https://www.indus-inhouse.com" style="color:#aaaaaa">Lead Management System</a><br><br><br></td></tr></table><!--/600px container --></td></tr></table><!--/100% background wrapper--></body></html>';
		
	}


	function getEmailBody($em_name,$lead_name,$lead_phone){
		return $body='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>New Lead Notification </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/></head><body style="margin:0; padding:0;" bgcolor="#999"> <table style="min-width:320px;" width="100%" cellspacing="0" cellpadding="0" bgcolor="#eaeced"> <table width="600" align="center" cellpadding="0" cellspacing="0"> <tr> <td style="padding:0px 20px;background-color: #fff;"> <table width="100%" cellpadding="0" cellspacing="0"> <tr> <th width="600" align="left" style="font:bold 25px/35px Arial, Helvetica, sans-serif; color:#222;padding-top:25px;"> New Lead Notification </th> </tr><tr> <th width="600" align="left" style="font: 14px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:3px;letter-spacing: 2.3px"> &copy; Lead Management System </th> <th width="10" style="padding:0;"></th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:20px;">Hi '.$em_name.', You have a new lead, Please login to the Lead Management System and review the lead. Please take an action now.</th> <th width="10" style="padding:0;"></th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:20px;padding-bottom: 5px;">Name :'.$lead_name.'</th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;">Phone : '.$lead_phone.'</th> </tr><tr> <td style="padding:30px 0 10px;"> <table align="left" style="margin:0 auto;" cellpadding="0" cellspacing="0"> <tr> <td data-size="size button" data-min="10" data-max="16" align="center" style=""> <table> <tr style="padding:30px 0 40px;"> <td width="140" style="font:16px/14px Arial, Helvetica, sans-serif; color:#f8f9fb; mso-padding-alt:12px 10px 10px; border-radius:2px;text-align:center; " bgcolor="#259356"><a target="_blank" style="text-decoration:none; color:#fff; display:block; padding:12px 10px 10px;" href="https://indus-inhouse.com/v20/ag/access/">Attend Now</a></td><td></td><td width="140" style="font:16px/14px Arial, Helvetica, sans-serif; color:#f8f9fb; mso-padding-alt:12px 10px 10px; border-radius:2px;text-align:center; " bgcolor="#fe9316"><a target="_blank" style="text-decoration:none; color:#fff; display:block; padding:12px 10px 10px;" href="https://indus-inhouse.com/v20/ag/access/">Hold</a></td></tr></table> </td></tr></table> </td></tr><tr> <th width="600" align="left" style="border-bottom:1px solid #eee;font: 12px/17px Arial, Helvetica, sans-serif; color:#222;padding-top:5px;"></th> </tr><tr> <td style="font:12px/16px Arial, Helvetica, sans-serif; color:#333; padding:20px 0px 0px;">Indus Real Estate LLC &copy; All Rights Reserved. </td></tr><tr> <td style="font:11px/16px Arial, Helvetica, sans-serif; color:#797c82; padding:10px 0px;"> You are receiving this email because you are a part of Indus Real Estate and setup to receive email notification. </td></tr></table> </td></tr></table></table></body></html>';		
	}






	function getEmailBodyTele($em_name){
		return $body='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>New Lead Notification </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/></head><body style="margin:0; padding:0;" bgcolor="#999"> <table style="min-width:320px;" width="100%" cellspacing="0" cellpadding="0" bgcolor="#eaeced"> <table width="600" align="center" cellpadding="0" cellspacing="0"> <tr> <td style="padding:0px 20px;background-color: #fff;"> <table width="100%" cellpadding="0" cellspacing="0"> <tr> <th width="600" align="left" style="font:bold 25px/35px Arial, Helvetica, sans-serif; color:#222;padding-top:25px;"> New Lead Notification </th> </tr><tr> <th width="600" align="left" style="font: 14px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:3px;letter-spacing: 2.3px"> &copy; Lead Management System </th> <th width="10" style="padding:0;"></th> </tr><tr> <th width="600" align="left" style="font: 15px/21px Arial, Helvetica, sans-serif; color:#222;padding-top:20px;">Hi '.$em_name.', You have new leads assigned to verify, Please login to the Lead Management System and review.</th> <th width="10" style="padding:0;"></th> </tr><tr> <td style="padding:30px 0 10px;"> <table align="left" style="margin:0 auto;" cellpadding="0" cellspacing="0"> <tr> <td data-size="size button" data-min="10" data-max="16" align="center" style=""> <table> <tr style="padding:30px 0 40px;"><td></td><td width="140" style="font:16px/14px Arial, Helvetica, sans-serif; color:#f8f9fb; mso-padding-alt:12px 10px 10px; border-radius:2px;text-align:center; " bgcolor="#fe9316"><a target="_blank" style="text-decoration:none; color:#fff; display:block; padding:12px 10px 10px;" href="https://www.indus-inhouse.com/v20/em/access/">Details</a></td></tr></table> </td></tr></table> </td></tr><tr> <th width="600" align="left" style="border-bottom:1px solid #eee;font: 12px/17px Arial, Helvetica, sans-serif; color:#222;padding-top:5px;"></th> </tr><tr> <td style="font:12px/16px Arial, Helvetica, sans-serif; color:#333; padding:20px 0px 0px;">Indus Real Estate LLC &copy; All Rights Reserved. </td></tr><tr> <td style="font:11px/16px Arial, Helvetica, sans-serif; color:#797c82; padding:10px 0px;"> You are receiving this email because you are a part of Indus Real Estate and setup to receive email notification. </td></tr></table> </td></tr></table></table></body></html>';		
	}



	function sendMail($body,$to,$subject) {
	    $profName='Lead Management System';
		$userName = 'noreply-lms@indus-inhouse.com';
		$password = 'E%OimvEy&asY';
		$transport = Swift_SmtpTransport::newInstance('mail.indus-inhouse.com',25,'')
		->setUsername($userName)
		->setPassword($password);
		$mMailer = Swift_Mailer::newInstance($transport);
		$mEmail = Swift_Message::newInstance();
		$mEmail->setSubject($subject);
		$mEmail->setTo($to);
		$mEmail->setFrom(array($userName => $profName));
		$mEmail->setBody($body, 'text/html');
		if($mMailer->send($mEmail) == 1){
			$send='ok';
		}
		else {
			$send='notok';
		}
		return $send;
	}





function sendSMSNew($to,$count){

if($to!=''){
	$agDet=$this->queryto_fetch("SELECT `phone`,`name` FROM `user` WHERE `userID`='$to' AND `status`=0 AND `type`='AG' ");
	if($agDet['phone']!=''){
	
	
	$phone = preg_replace('/\D/', '', $agDet['phone']);
// 	$phone='0526414233';

    
	$phone=ltrim($phone, '0');
	$phone='971'.$phone;
	

	$senderID='IndusRE';
	$profileID='20092939';
	$password='Mobi12@smsindus';	
	$name=mb_strimwidth($agDet['name'], 0, 20, ".");
	$sms_content="Hi ".$name.", You have new leads (".$count.") in LMS. Please click the Link for more details. https://bit.ly/34kyeUc";
	$sms_content=urlencode($sms_content);

	$url = "http://mshastra.com/sendurl.aspx?user=".$profileID."&pwd=".$password."&senderid=".$senderID."&mobileno=".$phone."&msgtext=".$sms_content."&CountryCode=ALL";
	$url=$url;
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$curl_scraped_page = curl_exec($ch);
	curl_close($ch);
	return $curl_scraped_page;
}
}
}









function sendSMS($to){

if($to!=''){
	$agDet=$this->queryto_fetch("SELECT `phone`,`name` FROM `user` WHERE `userID`='$to' AND `status`=0 AND `type`='AG' ");
	if($agDet['phone']!=''){
	
	
	$phone = preg_replace('/\D/', '', $agDet['phone']);
// 	$phone='0526414233';

    
	$phone=ltrim($phone, '0');
	$phone='971'.$phone;
	

	$senderID='IndusRE';
	$profileID='20092939';
	$password='Mobi12@smsindus';	
	$name=mb_strimwidth($agDet['name'], 0, 20, ".");
	$sms_content="Hi ".$name.", You have new leads in LMS. Please click the Link for more details. https://bit.ly/34kyeUc";
	$sms_content=urlencode($sms_content);

	$url = "http://mshastra.com/sendurl.aspx?user=".$profileID."&pwd=".$password."&senderid=".$senderID."&mobileno=".$phone."&msgtext=".$sms_content."&CountryCode=ALL";
	$url=$url;
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$curl_scraped_page = curl_exec($ch);
	curl_close($ch);
	return $curl_scraped_page;
}
}
}


function sendSMSTele($to){

if($to!=''){
	$agDet=$this->queryto_fetch("SELECT `phone`,`name` FROM `user` WHERE `userID`='$to' AND `status`=0 AND `type`='EM' ");
	if($agDet['phone']!=''){
	
	
	$phone = preg_replace('/\D/', '', $agDet['phone']);
// 	$phone='0526414233';

   
	$phone=ltrim($phone, '0');
	$phone='971'.$phone;
	

	$senderID='IndusRE';
	$profileID='20092939';
	$password='Mobi12@smsindus';	
	$name=mb_strimwidth($agDet['name'], 0, 20, ".");
	$sms_content="Hi ".$name.", You have new leads in LMS.Please log in for more details";
	$sms_content=urlencode($sms_content);

	$url = "http://mshastra.com/sendurl.aspx?user=".$profileID."&pwd=".$password."&senderid=".$senderID."&mobileno=".$phone."&msgtext=".$sms_content."&CountryCode=ALL";
	$url=$url;
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$curl_scraped_page = curl_exec($ch);
	curl_close($ch);
	return $curl_scraped_page;
}
}
}











	function deleteNotification($module,$from,$to,$leadID){
		if($module!='any'){ $qm=" AND `module`='$module' "; }else{ $qm=""; }
		if($from!='any'){ $qf=" AND `not_to`='$to' "; }else{ $qf=""; }
		if($to!='any'){ $qto=" AND `not_to`='$to' "; }else{ $qto=""; }
		$qurp=$qm.$qf.$qto;
		return $this->execute("DELETE FROM `indus_crm_notifications` WHERE `reference`='$leadID' ".$qurp);
	}







	function dateAnyFormat($intelDNT_v1,$format){
		$properDNT_outa=new DateTime($intelDNT_v1);
		return $properDNT_outa->format($format);
	}





	function login_App($login_sec_v1,$login_sec_v2){

		$login_sec_q="SELECT `id`,`userID`,`status`,`name`,`dp`,`email`,`phone` FROM `indus_crm_users` WHERE `username`='$login_sec_v1' AND `type`='AG' "; 
		$login_sec_r= $this->execute($login_sec_q);  
		$login_sec_n=mysqli_num_rows($login_sec_r);
		$status=0;
		if($login_sec_n==1){
// check the user account is locked or not(brutal attack escape)
			$locked=$this->checkBrute($login_sec_v1);

			if($locked>=5){
				$remaining_q="SELECT `dated` FROM `indus_crm_login_attempts` WHERE `username`='$login_sec_v1' AND `status`=1 ORDER BY `id` DESC LIMIT 1 ";
				$remaining_f=$this->queryto_fetch($remaining_q);
				$remaining_x=explode(' ', $remaining_f['dated']);
				$timestamp_remaining = strtotime($remaining_x[1]) + 60*60;
				$time_rem = date('H:i', $timestamp_remaining);

				$msg="Your account is blocked due to ".$locked." wrong attempts. Please try after ".$this->properTime($time_rem);       
			}
			else{
        // check the account activated or not
				$activated=$this->checkactivated($login_sec_v1);
				if($activated == 1){
					$login_sec_f=mysqli_fetch_array($login_sec_r);
					$userID=$login_sec_f['userID'];
					$login_sec_v2_md5=md5($login_sec_v2);
            // check Password
					$check_password_q="SELECT `id`,`userID`,`log` FROM `indus_crm_users` WHERE `userID`='$userID' AND `password`='$login_sec_v2_md5' "; 
					$check_password_r= $this->execute($check_password_q);  
					$check_password_n= mysqli_num_rows($check_password_r);  

					if($check_password_n==1){

						$check_password_f=mysqli_fetch_array($check_password_r); 
						
						$login_id=$check_password_f['id'];
						$login_log=$check_password_f['log'];
						$date_log=date("Y-m-d H:i");						
						$up_db_val=$date_log.'/unknown/App';

						$up_login_q="UPDATE `indus_crm_users` SET `log`='$up_db_val' WHERE `id`='$login_id' ";
						$up_login_r=$this->execute($up_login_q);
						$msg='Login Success, Welcome to LMS';
						$status=1;
					}
					else
					{
						$status=0;
						$attemptDate=date("Y-m-d H:i");
						$record_att_q="INSERT INTO `indus_crm_login_attempts` (`username`,`password`,`dated`,`status`,`userip`)VALUES('$login_sec_v1','$login_sec_v2','$attemptDate','1','App') "; 
						$record_att_r= $this->execute($record_att_q); 
						$locked_check_again=$this->checkBrute($login_sec_v1);
						$msg="Wrong Password , you have used ".$locked_check_again."/5 chances";

					}

				}   

				else { $msg="Your account is not activated  (or) suspended please contact the team"; }
			}
		}
		else{ $msg="No User found. The username you entered is wrong"; }

		if($status==1){
			$return=array('status'=>$status,'message'=>$msg,'userID'=>$userID,'name'=>$login_sec_f['name'],'dp'=>$login_sec_f['dp'],'email'=>$login_sec_f['email'],'phone'=>$login_sec_f['phone'] );
		}else{
			$return=array('status'=>$status,'message'=>$msg,'userID'=>'','name'=>'','dp'=>'','email'=>'','phone'=>'');
		}
		return $return;

	}


	function checkBrute($checkBrute_v1){
		$created_brute=date("Y-m-d H:i");
		return $checkBrute_n=$this->CountQuery("SELECT `id` FROM `indus_crm_login_attempts` WHERE TIMESTAMP(`dated`) BETWEEN DATE_SUB('$created_brute', INTERVAL 1 HOUR) AND '$created_brute'  AND (`username`='$checkBrute_v1' AND `status`=1 )");
	}


	function checkactivated($checkactivated_v1){
		$checkactivated_n=$this->CountQuery("SELECT `id` FROM `indus_crm_users` WHERE  `username`='$checkactivated_v1' AND `status`=0 ");
		return $checkactivated_n;
	}



	function getBrowser() { 
		$u_agent = $_SERVER['HTTP_USER_AGENT'];
		$bname = 'Unknown';
		$platform = 'Unknown';
		$version= "";
		
		//First get the platform?
		if (preg_match('/linux/i', $u_agent)) {
			$platform = 'linux';
		}elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
			$platform = 'mac';
		}elseif (preg_match('/windows|win32/i', $u_agent)) {
			$platform = 'windows';
		}
		
		// Next get the name of the useragent yes seperately and for good reason
		if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)){
			$bname = 'Internet Explorer';
			$ub = "MSIE";
		}elseif(preg_match('/Firefox/i',$u_agent)){
			$bname = 'Mozilla Firefox';
			$ub = "Firefox";
		}elseif(preg_match('/OPR/i',$u_agent)){
			$bname = 'Opera';
			$ub = "Opera";
		}elseif(preg_match('/Chrome/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
			$bname = 'Google Chrome';
			$ub = "Chrome";
		}elseif(preg_match('/Safari/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
			$bname = 'Apple Safari';
			$ub = "Safari";
		}elseif(preg_match('/Netscape/i',$u_agent)){
			$bname = 'Netscape';
			$ub = "Netscape";
		}elseif(preg_match('/Edge/i',$u_agent)){
			$bname = 'Edge';
			$ub = "Edge";
		}elseif(preg_match('/Trident/i',$u_agent)){
			$bname = 'Internet Explorer';
			$ub = "MSIE";
		}
		
		// finally get the correct version number
		$known = array('Version', $ub, 'other');
		$pattern = '#(?<browser>' . join('|', $known) .
		')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
		if (!preg_match_all($pattern, $u_agent, $matches)) {
		  // we have no matching number just continue
		}
		// see how many we have
		$i = count($matches['browser']);
		if ($i != 1) {
		  //we will have two since we are not using 'other' argument yet
		  //see if version is before or after the name
			if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
			  // $version= $matches['version'][0];
			}else {
			  // $version= $matches['version'][1];
			}
		}else {
		  // $version= $matches['version'][0];
		}
		
		// check if we have a number
		// if ($version==null || $version=="") {$version="?";}
		
		return array(
			'userAgent' => $u_agent,
			'name'      => $bname,
		  // 'version'   => $version,
			'platform'  => $platform,
			'pattern'    => $pattern
		);
	} 
	







	function utf8_converter($array){
		array_walk_recursive($array, function(&$item, $key){
			if(!mb_detect_encoding($item, 'utf-8', true)){
				$item = utf8_encode($item);
			}
		});
		
		return $array;
	}



	function get_lead_status($status){

		if($status=='U'){ $titles=array('Unattended'); $text='Leas is automatically assigned but lead owner did not attended the lead'; }
		if($status=='O'){ $titles=array('Lead Open'); $text='Lead is assigned , lead owner attended the lead and the lead is open'; }
		if($status=='F'){ $titles=array('Cancelled'); $text='Lead is assigned , lead owner attended the lead and Deal Cancelled'; }
		if($status=='C'){ $titles=array('Closed/Converted'); $text='Lead is assigned , lead owner attended the Deal is Converted / Closed'; }
		if($status=='E'){ $titles=array('Expired'); $text='Lead is assigned and lead expired due to the lack of response.'; }
		if($status=='N'){ $titles=array('New'); $text='Lead is assigned and lead expired due to the lack of response.'; }
			if($status=='T'){ $titles=array('Transfer Req'); $text='Agent requested to transfer the lead, Please assign to some other agent.'; }
		
		return array('titles'=>$titles,'content'=>$text);
	}


	function get_lead_status_agent($status){
		if($status=='U' ){ $color='warning'; $icon='error_outline'; $titles=array('Not Responded'); $text='Lead is assgined to you, not updated any response so far.'; }
		if($status=='C'){ $color='success'; $icon='check_circle'; $titles=array('Closed'); $text='You are updated a response on this Lead. Please check the timeline ro know more about your response.'; }
		if($status=='F'){ $color='danger'; $icon='error_circle'; $titles=array('Cancelled'); $text='You are updated a response on this Lead. Please check the timeline ro know more about your response.'; }
		if($status=='O'){ $color='blue'; $icon='error_circle'; $titles=array('Cancelled'); $text='You are updated a response on this Lead. Please check the timeline ro know more about your response.'; }
			if($status=='T'){ $titles=array('Transfer Req'); $text='Agent requested to transfer the lead, Please assign to some other agent.'; }
		return array('titles'=>$titles,'content'=>$text,'icon'=>$icon,'color'=>$color);
	}
	

	function scoreColor($score){
		if($score>=0 AND $score < 10 ){ $color="red"; }
		elseif($score>=10 AND $score < 20 ){ $color="orange"; }
		elseif($score>=20 AND $score < 40 ){ $color="warning"; }
		elseif($score>=40 AND $score < 60 ){ $color="primary"; }
		elseif($score>=60 AND $score <= 100 ){ $color="success"; }
		else { $color="dark"; }
		return array('color'=>$color);

	}
	
	
	public function scoreCalculate($id,$mode)
    {

        $leadData = $this->queryto_fetch_api("SELECT `email`,`phone`,`dev`,`com`,`rent_sale` FROM `lead` WHERE `id`='$id' ");
        $allData = $this->queryto_fetch_api("SELECT  `whatsapp`,`name_2`,`phone_2`,`designation`,`budget`,`property_type` FROM `lead_profile` WHERE `leadID`='$id' ");

        $score = 0;
        if (isset($allData['phone_2']) AND $allData['phone_2'] != '') {$score = $score + 10;}
        if (isset($allData['budget']) AND $allData['budget'] != '') {$score = $score + 10;}
        if (isset($allData['designation']) AND $allData['designation'] != '') {$score = $score + 10;}
        if (isset($allData['property_type']) AND $allData['property_type'] != '') {$score = $score + 10;}
        if (isset($allData['whatsapp']) AND $allData['whatsapp'] != '') {$score = $score + 10;}
        
        if (isset($leadData['rent_sale']) AND $leadData['rent_sale'] != '') {$score = $score + 10;}
        if (isset($leadData['dev']) AND $leadData['dev'] != '') {$score = $score + 10;}
        if (isset($leadData['com']) AND $leadData['com'] != '') {$score = $score + 10;}
        if (isset($leadData['phone']) AND $leadData['phone'] != '') {$score = $score + 10;}
        if (isset($leadData['email']) AND $leadData['email'] != '') {$score = $score + 10;}
        
        
        
        if($mode=='update'){
            
            $this->execute("UPDATE `lead` SET `score`='$score' WHERE `id`='$id' ");
        }
        
        return $score;

    }
	


}
?>