<?
function START_TRANSACTION(){
	mysql_query('START TRANSACTION');
}
function COMMIT(){
	mysql_query('COMMIT');
}
function ROLLBACK(){
	mysql_query('ROLLBACK');
}

function stayfocus($form,$objname,$objvalue) {
     print("<SCRIPT LANGUAGE=Javascript>");
     printf("for(i=0;i<document.%s.%s.options.length;i++) {",$form,$objname);
     printf("if(document.%s.%s.options[i].value==\"%s\")",$form,$objname,$objvalue);
     printf("document.%s.%s.options[i].selected=true",$form,$objname);
     print("}");
     print("</SCRIPT>"); 
}
function staymultifocus($form,$objname,$objvalue) {
	for($i=0;$i<count($objvalue);$i++){
     print("<SCRIPT LANGUAGE=Javascript>");
     printf("for(i=0;i<document.%s.%s.options.length;i++) {",$form,$objname);
     printf("if(document.%s.%s.options[i].value=='%s')",$form,$objname,$objvalue[$i]);
     printf("document.%s.%s.options[i].selected=true",$form,$objname);
     print("}");
     print("</SCRIPT>"); 
	} 
}
function email_notification($nm){
	$sql="select en_subject as subject,en_message as message from email_notification where en_name='$nm'";
	$result=mysql_query($sql);
	return $myrow=MySQL_fetch_array($result,MYSQL_ASSOC);
}
function system_date($date){
	list($d,$m,$y)=explode("/",$date);
	return $y."-".$m."-".$d;
}

function window_date($date){
	list($y,$m,$d)=explode("-",$date);
	return $d."/".$m."/".$y;
}
function record_valid($f,$t,$w){
	$sql="select $f from $t $w";
	$result=mysql_query($sql);
	$num_rows=mysql_num_rows($result);
	if($num_rows==0){
		return "FALSE";
	}else return "TRUE";
}


function get_data($f,$t,$w){
	$sql="select $f from $t $w";
	$result=mysql_query($sql) or die(mysql_error());
	$row=MySQL_fetch_array($result,MYSQL_ASSOC);
	return $row;
}

function record_num_rows($f,$t,$w){
	$sql="select $f from $t $w";
	$result=mysql_query($sql);
	return mysql_num_rows($result);
}


function nextid($f){
	$result=mysql_query("select $f from nextid");
	while($myrow=MySQL_fetch_array($result))
	     return $myrow[$f];	

}
function last_insert_id($idtype){
	$sql = "update nextid set $idtype =LAST_INSERT_ID($idtype+1)";
	if(!@mysql_query($sql))$mysql_error = mysql_error();
}

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message,$user,$cc,$bcc) {

	$message=str_replace("/UserFiles/$user/","http://crm.sepanggoldcoast.com/UserFiles/$user/",$message);
	$message=str_replace('\"','"',$message);

    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
//    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header = "From: ".$from_mail."\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    if($cc)$header .= "Cc: ".$cc."\r\n";
    if($bcc)$header .= "Bcc: ".$bcc."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/html; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
//        echo "mail send ... OK"; // or use booleans here
    } else {
//        echo  "mail send ... ERROR!";
    }
}
function mail_sent($mailto, $from_mail, $from_name, $replyto, $subject, $message,$user,$cc,$bcc) {

	$message=str_replace("/UserFiles/$user/","crm.sepanggoldcoast.com/UserFiles/$user/",$message);

	$message=str_replace('\"','"',$message);
    $uid = md5(uniqid(time()));
	
//    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header = "From: ".$from_mail."\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    if($cc)$header .= "Cc: ".$cc."\r\n";
    if($bcc)$header .= "Bcc: ".$bcc."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/html; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
	
	if (mail($mailto, $subject, "", $header)) {
   //     echo "mail send ... OK"; // or use booleans here
	} else {
	 //   echo  "mail send ... ERROR!";
	}
	

}
function position_value(){
	$sql="select * from newvalue where nv_type='Position'";
	$result=mysql_query($sql) or die(mysql_error());
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		$ret[$myrow["nv_id"]]=$myrow["nv_name"];

	return $ret;
}
function alert_sent($id,$type,$responder,$user){
//$_SERVER['DOCUMENT_ROOT']
	$my_path = DOCROOT."/uploads/$user/";
//	$my_name = NAME;
//	$my_mail = EMAIL;
//	$my_replyto = EMAIL;
	
	$stamp=nextid('n_eb');
	last_insert_id('n_eb');
	// search send 
	$sql="select * from eb_alert left join eb_template on eba_template=ebt_id where eba_id='$id'";
	$result=mysql_query($sql);	
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
	{
		$my_name = $myrow["eba_from"];
		$my_mail = $myrow["eba_from"];			
		$my_replyto = $myrow["eba_from"];
		$my_subject=$myrow["eba_subject"];				
		$cc=$myrow["eba_cc"];				
		$bcc=$myrow["eba_bcc"];				
		$my_message=$myrow["ebt_msg"];		
		$my_file=$myrow["ebt_attach"];		

		//person
		if($myrow["eba_pselect"]=="All")$psql="1";
		else if($myrow["eba_pselect"]=="Individual"){
			if($myrow["eba_title"]>1)$psql_ar[]="p_title='".$myrow["eba_title"]."'";
			if($myrow["eba_role"]>1)$psql_ar[]="p_role='".$myrow["eba_role"]."'";
			if($myrow["eba_race"]>1)$psql_ar[]="p_race='".$myrow["eba_race"]."'";
			if($myrow["eba_status"]>1)$psql_ar[]="p_status='".$myrow["eba_status"]."'";
			if($myrow["eba_gender"]>1)$psql_ar[]="p_gender='".$myrow["eba_gender"]."'";
			if($myrow["eba_ageformula"] && $myrow["eba_age"] > 0){
				$dob=date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")-$myrow["eba_age"]));
				$psql_ar[]="p_dob ".$myrow["eba_ageformula"]." '$dob'";
			}
			if($myrow["eba_type"]>1)$psql_ar[]="p_type='".$myrow["eba_type"]."'";
			if($myrow["eba_industry"]>1)$psql_ar[]="p_industry='".$myrow["eba_industry"]."'";
			if($myrow["eba_source"]>1)$psql_ar[]="p_source='".$myrow["eba_source"]."'";
			if($myrow["eba_classification"]>1)$psql_ar[]="p_classification='".$myrow["eba_classification"]."'";
			if($myrow["eba_country"])$psql_ar[]="p_country='".$myrow["eba_country"]."'";
		}	
		//company
		if($myrow["eba_cselect"]=="All")$csql="1";
		else if($myrow["eba_cselect"]=="Individual"){
			if($myrow["eba_cband"]>1)$csql_ar[]="c_band='".$myrow["eba_cband"]."'";
			if($myrow["eba_ctype"]>1)$csql_ar[]="c_type='".$myrow["eba_ctype"]."'";
			if($myrow["eba_cindustry"]>1)$csql_ar[]="c_industry='".$myrow["eba_cindustry"]."'";
			if($myrow["eba_csource"]>1)$csql_ar[]="c_source='".$myrow["eba_csource"]."'";
			if($myrow["eba_cclassification"]>1)$csql_ar[]="c_classification='".$myrow["eba_cclassification"]."'";
			if($myrow["eba_ccountry"])$csql_ar[]="c_country='".$myrow["eba_ccountry"]."'";
		}
		$p_dear=$myrow["eba_pdear"];
		$c_dear=$myrow["eba_cdear"];
	}	
	
	//send person
	if(count($psql_ar)>0)$psql=implode(" and ",$psql_ar);

	if($psql){
		$sql="select p_id,p_name,p_email1,p_email2,p_email3 from person where $psql and p_active='Yes' and (p_email1<>'' or p_email2<>'' or p_email3<>'')"; 
		$result=mysql_query($sql) or die(mysql_error());
		$pnum=mysql_num_rows($result);
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{
			$email=$myrow["p_email1"]."#".$myrow["p_email2"]."#".$myrow["p_email3"];
			$grprcp[]=$myrow["p_id"]."|".$myrow["p_name"]."|$email";
			
		}		
		$k=0;
		if(count($grprcp)>0){
			for($i=0;$i<count($grprcp);$i++)
			{
				$k++;
				unset($gemail);				
				list($pid,$pname,$pemail)=explode("|",$grprcp[$i]);
				$gemail=explode("#",$pemail);
				if($p_dear=="name")$disname=$pname;
				else if($p_dear=="default")$disname="Valued Customer";

				if($k==10){
					sleep(3);
					$k=1;
				}
				for($j=0;$j<count($gemail);$j++){
					$mailto=$gemail[$j];
				
					if($mailto){

						$header='<img src="http://crm.sepanggoldcoast.com/images/iconic-logo.png"><img src="http://crm.sepanggoldcoast.com/eb_open.php?stamp='.$stamp.'&eb='.$id.'&r='.$pid.'&e='.$mailto.'&user='.$user.'&type=person&responder='.$responder.'" width="0" height="0"><br><br>';
						$msg=$header.'<br><br><font size="3">Dear '.$disname.',</font><br><br>'.$my_message;
						
						$sql="insert into contact_temp (name,email) values ('$user','$mailto')";
						@mysql_query($sql) or die(mysql_error());
					//	if($my_file)mail_attachment($my_file, $my_path, $mailto, $my_mail, $my_name, $my_replyto, $my_subject, $msg, $user,$cc,$bcc);
					//	else mail_sent($mailto, $my_mail, $my_name, $my_replyto, $my_subject, $msg, $user,$cc,$bcc);
					}
				}
			}
		}
	}

	// company
	if(count($csql_ar)>0)$csql=implode(" and ",$csql_ar);
	unset($grprcp);
	if($csql){
		$sql="select c_id,c_person,c_email1,c_email2,c_email3 from company where $csql and c_active='Yes' and (c_email1<>'' or c_email2<>'' or c_email3<>'')"; 
		$result=mysql_query($sql) or die(mysql_error());
		$cnum=mysql_num_rows($result);
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{
			$email=$myrow["c_email1"]."#".$myrow["c_email2"]."#".$myrow["c_email3"];
			if($myrow["c_person"])$dnm=$myrow["c_person"];
			else $dnm="<font size='2'>Valued Customer</font>";
			$grprcp[]=$myrow["c_id"]."|$dnm|$email";
			
		}		
		$k=0;
		if(count($grprcp)>0){
			for($i=0;$i<count($grprcp);$i++)
			{
				$k++;
				unset($gemail);
				list($pid,$pname,$pemail)=explode("|",$grprcp[$i]);
				$gemail=explode("#",$pemail);
				if($c_dear=="name")$disname=$pname;
				else if($c_dear=="default")$disname="Valued Customer";

				if($k==10){
					sleep(3);
					$k=1;
				}

				for($j=0;$j<count($gemail);$j++){
					$mailto=$gemail[$j];

					if($mailto){
						//$cnum++;	
						$header='<img src="http://crm.sepanggoldcoast.com/images/iconic-logo.png"><img src="http://crm.sepanggoldcoast.com/eb_open.php?stamp='.$stamp.'&eb='.$id.'&r='.$pid.'&e='.$mailto.'&user='.$user.'&type=company&responder='.$responder.'" width="0" height="0"><br><br>';
						$msg=$header."Dear $disname,<br><br>".$my_message;

						$sql="insert into contact_temp (name,email) values ('$user','$mailto')";
						@mysql_query($sql) or die(mysql_error());

					//	if($my_file)mail_attachment($my_file, $my_path, $mailto, $my_mail, $my_name, $my_replyto, $my_subject, $msg, $user,$cc,$bcc);
					//	else mail_sent($mailto, $my_mail, $my_name, $my_replyto, $my_subject, $msg, $user,$cc,$bcc);
					}
				}
			}
		}
	}


	$tot=$pnum + $cnum;
	$sql="
		INSERT INTO `eb_alertsent` (
		`ebas_alert` ,`ebas_type` ,ebas_stamp,
		`ebas_created` ,ebas_record
		)
		VALUES ('$id','$type','$stamp',CURRENT_TIMESTAMP,'$tot'
		);
	";
	@mysql_query($sql) or die(mysql_error());
	
	if($type=="Now"){
		$sql="
		UPDATE `eb_alert` SET 
		`eba_senddate` ='0000-00-00'
		 WHERE `eb_alert`.`eba_id` ='$id'";
		@mysql_query($sql) or die(mysql_error());
				
	}

}

function alert_birthday($id,$type,$responder,$dob,$type,$user){
	$my_path = $_SERVER['DOCUMENT_ROOT']."/uploads/$user/";
//	$my_name = NAME;
//	$my_mail = EMAIL;
//	$my_replyto = EMAIL;
	
	$stamp=nextid('n_eb');
	last_insert_id('n_eb');
	// search send 
	 $sql="select * from eb_alert left join eb_template on eba_template=ebt_id where eba_id='$id'";
	$result=mysql_query($sql);	
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
	{
		$my_name = $myrow["eba_from"];
		$my_mail = $myrow["eba_from"];			
		$my_replyto = $myrow["eba_from"];
		$my_subject=$myrow["eba_subject"];				
		$cc=$myrow["eba_cc"];				
		$bcc=$myrow["eba_bcc"];				

		$my_message=$myrow["ebt_msg"];		
		$my_file=$myrow["ebt_attach"];		
		
		//person
		if($myrow["eba_pselect"]=="All")$psql="1";
		else if($myrow["eba_pselect"]=="Individual"){
			if($myrow["eba_title"]>1)$psql_ar[]="p_title='".$myrow["eba_title"]."'";
			if($myrow["eba_role"]>1)$psql_ar[]="p_role='".$myrow["eba_role"]."'";
			if($myrow["eba_race"]>1)$psql_ar[]="p_race='".$myrow["eba_race"]."'";
			if($myrow["eba_status"]>1)$psql_ar[]="p_status='".$myrow["eba_status"]."'";
			if($myrow["eba_gender"]>1)$psql_ar[]="p_gender='".$myrow["eba_gender"]."'";
			if($myrow["eba_ageformula"] && $myrow["eba_age"] > 0){
				$dob=date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")-$myrow["eba_age"]));
				$psql_ar[]="p_dob ".$myrow["eba_ageformula"]." '$dob'";
			}
			if($myrow["eba_type"]>1)$psql_ar[]="p_type='".$myrow["eba_type"]."'";
			if($myrow["eba_industry"]>1)$psql_ar[]="p_industry='".$myrow["eba_industry"]."'";
			if($myrow["eba_source"]>1)$psql_ar[]="p_source='".$myrow["eba_source"]."'";
			if($myrow["eba_classification"]>1)$psql_ar[]="p_classification='".$myrow["eba_classification"]."'";
			if($myrow["eba_country"])$psql_ar[]="p_country='".$myrow["eba_country"]."'";
		}	
		
		$p_dear=$myrow["eba_pdear"];

	}	
	
	//send person
	if(count($psql_ar)>0)$psql=implode(" and ",$psql_ar);

	if($psql){

		if($type=="dob"){

			if($dob=="99"){
				$sql="select p_id,p_name,p_email1,p_email2,p_email3 from person where $psql and substring(p_dob,6)='".date("m-d")."' and p_active='Yes' and (p_email1<>'' or p_email2<>'' or p_email3<>'')"; 
			}else{
				$sql="select p_id,p_name,p_email1,p_email2,p_email3 from person where $psql and substring(DATE_SUB(p_dob, INTERVAL $dob DAY),6)='".date("m-d")."' and p_active='Yes' and (p_email1<>'' or p_email2<>'' or p_email3<>'')"; 
			}
		}else if($type=="spdob"){
			if($dob=="99"){
				$sql="select p_id,p_name,p_email1,p_email2,p_email3 from person where $psql and substring(p_spdob,6)='".date("m-d")."' and p_active='Yes' and (p_email1<>'' or p_email2<>'' or p_email3<>'')"; 
			}else{
				$sql="select p_id,p_name,p_email1,p_email2,p_email3 from person where $psql and substring(DATE_SUB(p_spdob, INTERVAL $dob DAY),6)='".date("m-d")."' and p_active='Yes' and (p_email1<>'' or p_email2<>'' or p_email3<>'')"; 
			}

		}	
		$result=mysql_query($sql) or die(mysql_error());
		$pnum=mysql_num_rows($result);
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{
			$email=$myrow["p_email1"]."#".$myrow["p_email2"]."#".$myrow["p_email3"];
			$grprcp[]=$myrow["p_id"]."|".$myrow["p_name"]."|$email";
			
		}		
		if(count($grprcp)>0){
			for($i=0;$i<count($grprcp);$i++)
			{
				unset($gemail);
				list($pid,$pname,$pemail)=explode("|",$grprcp[$i]);
				$gemail=explode("#",$pemail);
				if($p_dear=="name")$disname=$pname;
				else if($p_dear=="default")$disname="Valued Customer";

				for($j=0;$j<count($gemail);$j++){
					if($gemail[$j]){
						$mailto=$gemail[$j];
						if($mailto){
							$header='<img src="http://crm.sepanggoldcoast.com/images/logo.jpg"><img src="http://crm.sepanggoldcoast.com/eb_open.php?stamp='.$stamp.'&eb='.$id.'&r='.$pid.'&e='.$mailto.'&user='.$user.'&type=person&responder='.$responder.'" width="0" height="0"><br><br>';
							$msg=$header."Dear $disname,<br><br>".$my_message;
		
							if($my_file)mail_attachment($my_file, $my_path, $mailto, $my_mail, $my_name, $my_replyto, $my_subject, $msg, $user,$cc,$bcc);
							else mail_sent($mailto, $my_mail, $my_name, $my_replyto, $my_subject, $msg, $user,$cc,$bcc);
						}
					}
				}
			}
		}
	}


	$tot=$pnum;
	if($tot >0){
		$sql="
			INSERT INTO `eb_alertsent` (
			`ebas_alert` ,`ebas_type` ,ebas_stamp,
			`ebas_created` ,ebas_record
			)
			VALUES ('$id','$type','$stamp',CURRENT_TIMESTAMP,'$tot'
			);
		";
		@mysql_query($sql) or die(mysql_error());
		
	
	}
}
function httpRequest($url){
  $pattern = "/http...([0-9a-zA-Z-.]*).([0-9]*).(.*)/";
    preg_match($pattern,$url,$args);
    $in = "";

	 $args[3]="w".$args[3];

//    $fp = fsockopen("$args[1]", $args[2], $errno, $errstr, 30);
    $fp = fsockopen("$args[1]", 80, $errno, $errstr, 30);
    if (!$fp) {
       return("$errstr ($errno)");
    } else {
        $out = "GET /$args[3] HTTP/1.1\r\n";
        $out .= "Host: $args[1]:$args[2]\r\n";
        $out .= "User-agent: BulkSMS2u PHP client\r\n";
   
        $out .= "Accept: */*\r\n";
        $out .= "Connection: Close\r\n\r\n";

        fwrite($fp, $out);
        while (!feof($fp)) {
          // $in.=fgets($fp, 128);
           $in=fgets($fp, 128);
        }
    }
  
    fclose($fp);
    return($in);

}



function SMSalert_sent($id,$type,$user){

	$debug = false;

	$ret=get_data("nv_id","newvalue","where nv_name='MOBILE'");
	$mobile=$ret["nv_id"];
	
	$stamp=nextid('n_sms');
	last_insert_id('n_sms');
	// search send 
	$sql="select * from sms_alert where smsa_id='$id'";
	$result=mysql_query($sql);	
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
	{
		//person
		if($myrow["smsa_pselect"]=="All")$psql="1";
		else if($myrow["smsa_pselect"]=="Individual"){
			if($myrow["smsa_title"]>1)$psql_ar[]="p_title='".$myrow["smsa_title"]."'";
			if($myrow["smsa_role"]>1)$psql_ar[]="p_role='".$myrow["smsa_role"]."'";
			if($myrow["smsa_race"]>1)$psql_ar[]="p_race='".$myrow["smsa_race"]."'";
			if($myrow["smsa_status"]>1)$psql_ar[]="p_status='".$myrow["smsa_status"]."'";
			if($myrow["smsa_gender"]>1)$psql_ar[]="p_gender='".$myrow["smsa_gender"]."'";
			if($myrow["smsa_ageformula"] && $myrow["smsa_age"] > 0){
				$dob=date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")-$myrow["smsa_age"]));
				$psql_ar[]="p_dob ".$myrow["smsa_ageformula"]." '$dob'";
			}
			if($myrow["smsa_type"]>1)$psql_ar[]="p_type='".$myrow["smsa_type"]."'";
			if($myrow["smsa_industry"]>1)$psql_ar[]="p_industry='".$myrow["smsa_industry"]."'";
			if($myrow["smsa_source"]>1)$psql_ar[]="p_source='".$myrow["smsa_source"]."'";
			if($myrow["smsa_classification"]>1)$psql_ar[]="p_classification='".$myrow["smsa_classification"]."'";
			if($myrow["smsa_country"])$psql_ar[]="p_country='".$myrow["smsa_country"]."'";
		}	
		//company
		if($myrow["smsa_cselect"]=="All")$csql="1";
		else if($myrow["smsa_cselect"]=="Individual"){
			if($myrow["smsa_cband"]>1)$csql_ar[]="c_band='".$myrow["smsa_cband"]."'";
			if($myrow["smsa_ctype"]>1)$csql_ar[]="c_type='".$myrow["smsa_ctype"]."'";
			if($myrow["smsa_cindustry"]>1)$csql_ar[]="c_industry='".$myrow["smsa_cindustry"]."'";
			if($myrow["smsa_csource"]>1)$csql_ar[]="c_source='".$myrow["smsa_csource"]."'";
			if($myrow["smsa_cclassification"]>1)$csql_ar[]="c_classification='".$myrow["smsa_cclassification"]."'";
			if($myrow["smsa_ccountry"])$csql_ar[]="c_country='".$myrow["smsa_ccountry"]."'";
		}
//		$p_dear=$myrow["smsa_pdear"];
//		$c_dear=$myrow["smsa_cdear"];
	}	
	
	$n=0;
	//send person
	if(count($psql_ar)>0)$psql=implode(" and ",$psql_ar);
	
	
	if($psql){
		$sql="select p_id,p_name,p_phone1,p_phone1_label,p_phone2,p_phone2_label,p_phone3,p_phone3_label from person where
		 $psql and p_active='Yes' and ((p_phone1<>'' && p_phone1_label='$mobile') or (p_phone2<>'' && p_phone2_label='$mobile') or (p_phone3<>'' && p_phone3_label='$mobile')) and p_user='$user'"; 
		$result=mysql_query($sql) or die(mysql_error());
	//	$pnum=mysql_num_rows($result);
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{
			unset($phone);
			if($myrow["p_phone1_label"]==$mobile && $myrow["p_phone1"]){
				$phone=$myrow["p_phone1"];
			}
			if($myrow["p_phone2_label"]==$mobile && $myrow["p_phone2"]){
				if($phone)$phone.="#".$myrow["p_phone2"];
				else $phone=$myrow["p_phone2"];
			}
			if($myrow["p_phone3_label"]==$mobile && $myrow["p_phone3"]){
				if($phone)$phone.="#".$myrow["p_phone3"];
				else $phone=$myrow["p_phone3"];
			}

			$grprcp[]=$myrow["p_id"]."|".$myrow["p_name"]."|$phone";
			
		}		

		if(count($grprcp)>0){
			for($i=0;$i<count($grprcp);$i++)
			{
				list($pid,$pname,$phone)=explode("|",$grprcp[$i]);
				$gphone=explode("#",$phone);
//				if($p_dear=="name")$disname=$pname;
//				else if($p_dear=="default")$disname="Valued Customer";

				for($j=0;$j<count($gphone);$j++){
					$phonenum=$gphone[$j];
					if($phonenum){	

						$sql="
							INSERT INTO `sms_outbox` (smso_stamp,
							`smso_alert` ,smso_phone,smso_name,`smso_created` ,smso_status,smso_user)
							VALUES ('$stamp','$id','$phonenum','$pname',CURRENT_TIMESTAMP,'Pending','$user'
							);
							";
						@mysql_query($sql) or die(mysql_error());

						$n++;
					}
				}
			}
		}
	}

	// company
	if(count($csql_ar)>0)$csql=implode(" and ",$csql_ar);
	unset($grprcp);
	if($csql){
		$sql="select c_id,c_name,c_phone1,c_phone1_label,c_phone2,c_phone2_label,c_phone3,c_phone3_label from company
		 where $csql and c_active='Yes' and ((c_phone1<>'' && c_phone1_label='$mobile') or (c_phone2<>'' && c_phone2_label='$mobile') or (c_phone3<>'' && c_phone3_label='$mobile'))"; 
		$result=mysql_query($sql) or die(mysql_error());
		$cnum=mysql_num_rows($result);
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{
			unset($phone);		
			if($myrow["c_phone1_label"]==$mobile && $myrow["c_phone1"]){
				$phone=$myrow["c_phone1"];
			}
			if($myrow["c_phone2_label"]==$mobile && $myrow["c_phone2"]){
				if($phone)$phone.="#".$myrow["c_phone2"];
				else $phone=$myrow["c_phone2"];
			}
			if($myrow["c_phone3_label"]==$mobile && $myrow["c_phone3"]){
				if($phone)$phone.="#".$myrow["c_phone3"];
				else $phone=$myrow["c_phone3"];
			}
			
			$dnm=$myrow["c_name"];
//			if($myrow["c_person"])$dnm=$myrow["c_person"];
	//		else $dnm="Valued Customer";
			$grprcp[]=$myrow["c_id"]."|$dnm|$phone";
			
		}		
		if(count($grprcp)>0){
			for($i=0;$i<count($grprcp);$i++)
			{
				list($pid,$pname,$phone)=explode("|",$grprcp[$i]);
				$gphone=explode("#",$phone);
//				if($c_dear=="name")$disname=$pname;
//				else if($c_dear=="default")$disname="Valued Customer";

				for($j=0;$j<count($gphone);$j++){
					$phonenum=$gphone[$j];
					if($phonenum){

						$sql="
							INSERT INTO `sms_outbox` (smso_stamp,
							`smso_alert` ,smso_phone,smso_name,`smso_created` ,smso_status,smso_user)
							VALUES ('$stamp','$id','$phonenum','$pname',CURRENT_TIMESTAMP,'Pending','$user'
							);
							";
						@mysql_query($sql) or die(mysql_error());	
						
						$n++;
					}
				}
			}
		}
		
	}



		
	if($type=="Now"){
		$sql="
		UPDATE `sms_alert` SET 
		`smsa_senddate` ='0000-00-00'
		 WHERE `smsa_id` ='$id'";
		@mysql_query($sql) or die(mysql_error());
	}		
	return $n;	
	
}

function SendSMS($phone, $msg, $debug=false, $sender){
//      global $bulksms2u_user,$bulksms2u_password,$bulksms2u_url;
//echo ">>>>>>>>>>>>".SMS_USER;
	$bulksms2u_user = SMS_USER;
	$bulksms2u_password = SMS_PWD;
	$bulksms2u_url = SMS_API;
	  

      $url = 'username='.$bulksms2u_user;
      $url.= '&password='.$bulksms2u_password;
      $url.= '&sender='.$sender;
      $url.= '&type=1';
      $url.= '&mobile='.urlencode($phone);
      $url.= '&message='.urlencode($msg);

      $urltouse =  $bulksms2u_url.$url;
      if ($debug) { echo "Request: <br>$urltouse<br><br>"; }

      //Open the URL to send the message
      $response = httpRequest($urltouse);
      if ($debug) {
           echo "Response: <br><pre>".
           str_replace(array("<",">"),array("&lt;","&gt;"),$response).
           "</pre><br>"; }

      return($response);
}
function SMSalert_birthday($id,$type,$dob,$type,$user){
	$debug = false;

	$ret=get_data("nv_id","newvalue","where nv_name='MOBILE'");
	$mobile=$ret["nv_id"];
	
	$stamp=nextid('n_sms');
	last_insert_id('n_sms');
	// search send 
	$sql="select * from sms_alert left join sms_template on smsa_template=smst_id where smsa_id='$id'";
	$result=mysql_query($sql);	
	while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
	{
		$sender=$myrow["smsa_sender"];		
		$message=$myrow["smst_msg"];		
		//person
		if($myrow["smsa_pselect"]=="All")$psql="1";
		else if($myrow["smsa_pselect"]=="Individual"){
			if($myrow["smsa_title"]>1)$psql_ar[]="p_title='".$myrow["smsa_title"]."'";
			if($myrow["smsa_role"]>1)$psql_ar[]="p_role='".$myrow["smsa_role"]."'";
			if($myrow["smsa_race"]>1)$psql_ar[]="p_race='".$myrow["smsa_race"]."'";
			if($myrow["smsa_status"]>1)$psql_ar[]="p_status='".$myrow["smsa_status"]."'";
			if($myrow["smsa_gender"]>1)$psql_ar[]="p_gender='".$myrow["smsa_gender"]."'";
			if($myrow["smsa_ageformula"] && $myrow["smsa_age"] > 0){
				$dob=date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")-$myrow["smsa_age"]));
				$psql_ar[]="p_dob ".$myrow["smsa_ageformula"]." '$dob'";
			}
			if($myrow["smsa_type"]>1)$psql_ar[]="p_type='".$myrow["smsa_type"]."'";
			if($myrow["smsa_industry"]>1)$psql_ar[]="p_industry='".$myrow["smsa_industry"]."'";
			if($myrow["smsa_source"]>1)$psql_ar[]="p_source='".$myrow["smsa_source"]."'";
			if($myrow["smsa_classification"]>1)$psql_ar[]="p_classification='".$myrow["smsa_classification"]."'";
			if($myrow["smsa_country"])$psql_ar[]="p_country='".$myrow["smsa_country"]."'";
		}	

		$p_dear=$myrow["smsa_pdear"];
	}	

	//send person
	if(count($psql_ar)>0)$psql=implode(" and ",$psql_ar);

	if($psql){

		if($type=="dob"){

			if($dob=="99"){
				$sql="select p_id,p_name,p_phone1,p_phone1_label,p_phone2,p_phone2_label,p_phone3,p_phone3_label from person where $psql and substring(p_dob,6)='".date("m-d")."' and p_active='Yes' and ((p_phone1<>'' && p_phone1_label='$mobile') or (p_phone2<>'' && p_phone2_label='$mobile') or (p_phone3<>'' && p_phone3_label='$mobile')) and p_user='$user'"; 
			}else{
				$sql="select p_id,p_name,p_phone1,p_phone1_label,p_phone2,p_phone2_label,p_phone3,p_phone3_label from person where $psql and substring(DATE_SUB(p_dob, INTERVAL $dob DAY),6)='".date("m-d")."' and p_active='Yes' and ((p_phone1<>'' && p_phone1_label='$mobile') or (p_phone2<>'' && p_phone2_label='$mobile') or (p_phone3<>'' && p_phone3_label='$mobile')) and p_user='$user'"; 
			}
		}else if($type=="spdob"){
			if($dob=="99"){
				$sql="select p_id,p_name,p_phone1,p_phone1_label,p_phone2,p_phone2_label,p_phone3,p_phone3_label from person where $psql and substring(p_spdob,6)='".date("m-d")."' and p_active='Yes' and ((p_phone1<>'' && p_phone1_label='$mobile') or (p_phone2<>'' && p_phone2_label='$mobile') or (p_phone3<>'' && p_phone3_label='$mobile')) and p_user='$user'"; 
			}else{
				$sql="select p_id,p_name,p_phone1,p_phone1_label,p_phone2,p_phone2_label,p_phone3,p_phone3_label from person where $psql and substring(DATE_SUB(p_spdob, INTERVAL $dob DAY),6)='".date("m-d")."' and p_active='Yes' and ((p_phone1<>'' && p_phone1_label='$mobile') or (p_phone2<>'' && p_phone2_label='$mobile') or (p_phone3<>'' && p_phone3_label='$mobile')) and p_user='$user'"; 
			}

		}	
		$result=mysql_query($sql) or die(mysql_error());
		$pnum=mysql_num_rows($result);
		while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))
		{
			if($myrow["p_phone1_label"]==$mobile && $myrow["p_phone1"]){
				$phone=$myrow["p_phone1"];
			}
			if($myrow["p_phone2_label"]==$mobile && $myrow["p_phone2"]){
				if($phone)$phone.="#".$myrow["p_phone2"];
				else $phone=$myrow["p_phone2"];
			}
			if($myrow["p_phone3_label"]==$mobile && $myrow["p_phone3"]){
				if($phone)$phone.="#".$myrow["p_phone3"];
				else $phone=$myrow["p_phone3"];
			}

			$grprcp[]=$myrow["p_id"]."|".$myrow["p_name"]."|$phone";
		
		}		
		if(count($grprcp)>0){
			for($i=0;$i<count($grprcp);$i++)
			{
				list($pid,$pname,$phone)=explode("|",$grprcp[$i]);
				$gphone=explode("#",$phone);

				for($j=0;$j<count($gphone);$j++){
					$phonenum=$gphone[$j];
					if($phonenum){
						$msg=$message;
					//	$res=SendSMS($phonenum,$msg,$debug, $sender);
						
						$status=$res;
						if($res=="1701")$status="Success";
						else $status="Failure";
						$sql="
							INSERT INTO `sms_alertsent` (
							`smsas_alert` ,`smsas_type` ,smsas_stamp,
							`smsas_created` ,smsas_status,smsas_user,smsas_phone)
							VALUES ('$id','$type','$stamp',CURRENT_TIMESTAMP,'$status','$user','$phonenum'
							);
							";
						@mysql_query($sql) or die(mysql_error());


					}
				}
			}
		}
	}

}
function insert_log($user,$desc){
	$sql="insert into log (l_user,l_desc) values ('$user',\"$desc\")";
	@mysql_query($sql) or die(mysql_error());
}


function destroy($dir) {

	$mydir = opendir($dir);
	while(false !== ($file = readdir($mydir))) {
		if($file != "." && $file != "..") {
			chmod($dir.$file, 0777);
			if(is_dir($dir.$file)) {
				chdir('.');
				destroy($dir.$file.'/');
				rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
            }else unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
		}
	 }
	 closedir($mydir);
}
function SMSBalance(){
      $url = 'username='.SMS_USER;
      $url.= '&password='.SMS_PWD;
      $urltouse =  SMS_BAL.$url;
      //Open the URL to send the message
      return httpRequest($urltouse);
}
?>
