<?php
		/*if(!file_exists("/home/steelmin/public_html/newtestfolder12")) {
				mkdir("/home/steelmin/public_html/finalfolder", 0777);  
				//echo "1. New Directory : <br />";			
		} else {
			  rename("/home/steelmin/public_html/newtestfolder12","/home/steelmin/public_html/finalfolder");
			// echo "Rename Directory : ".$folder['folder_name'] ."<br />";	
		}*/
	set_time_limit(0);
	$timezone = new DateTimeZone( "Asia/Calcutta" );
	$date = new DateTime();
	$date->setTimezone( $timezone );
	$currTime=$date->format( 'H:i:s' );
	$currMonth=$date->format( 'M' );
	$currMonth=$date->format( 'M' );
	$currDateTime=$date->format( 'Y-m-d H:i:s' );
	$dayOfWeek = date( "D", strtotime($currDateTime));
	
	
	//file_get_contents("https://www.steelmint.com/registrationAJAX.php?sendSARVmails=Y&events=N");
	
	/* 
	if( strpos($currTime, '17:07:') !== false)
	{
		//echo $msgs=file_get_contents("https://www.steelmint.com/daily_report/global_prices_report.php");
		$mystring = get_curl_data("https://www.steelmint.com/daily_report/global_prices_report.php");

		echo $mystring;
		
	} */
	
	/* if( strpos($currTime, '16:22:') !== false)
	{
		require_once "/home/steelmin/public_html/inc/config1.php"; 	
		//ini_set('display_errors',1);
		require_once "/home/steelmin/public_html/mf.php"; 


		$msgs=file_get_contents("https://www.steelmint.com/indian_steel_prices.php");

		sendSMMail($msgs, 'mohan@steelmint.com', $name='', $subject="SteelMint : indian_steel_prices.php");
		//include "inc/desconfig.php";	
		require_once('/home/steelmin/public_html/inc/desconfig.php');
	} */

	if( strpos($currTime, '15:06:') !== false || strpos($currTime, '20:06:') !== false )
	{
		require_once "/home/steelmin/public_html/inc/config1.php"; 	
		include "/home/steelmin/public_html/hf.php";

		$memid = qryToCommaSepString("
		
			select distinct memid
			from tbl_updated_reg_logs
			where services in ('W', 'S')
			
		");

		$ids = qryToCommaSepString("
		
			select distinct id
			from tbl_members
			where id not in ($memid)
			
		");

		$a = explode(",", $ids);
		for($i = 0; $i < count($a); $i++){
			
			mysql_query( "insert into tbl_updated_reg_logs (created_on, memid, services, paid_unpaid, status, nonactive_products, mod_srvc_name)
			values (NOW(), " . $a[$i] . ", 'W', 'not_active', 'Inactive', 'Tmporarily created 2016-09-17', 'webservice')");
		}

		include "/home/steelmin/public_html/inc/desconfig.php";
		die;
	}
		
	if( strpos($currTime, '15:00:') !== false && "Sat" == $dayOfWeek)
	{
		require_once "/home/steelmin/public_html/inc/config1.php"; 	
		//ini_set('display_errors',1);
		require_once "/home/steelmin/public_html/mf.php"; 


		$msgs=' <a href="https://www.steelmint.com/daily_report/global_prices_report.php">Click here</a> to send Global Steel Trade Mailer';
		//echo $msgs;

		sendSMMail($msgs, 'tarun@steelmint.com', $name='', $subject="SteelMint : Global Steel Prices reminder link");
		//include "inc/desconfig.php";	
		require_once('/home/steelmin/public_html/inc/desconfig.php');
	}


	if( strpos($currTime, '11:00:') !== false || strpos($currTime, '12:00:') !== false || strpos($currTime, '13:00:') !== false || strpos($currTime, '14:10:') !== false || strpos($currTime, '16:10:') !== false || strpos($currTime, '17:20:') !== false || strpos($currTime, '18:10:') !== false || strpos($currTime, '20:10:') !== false)
	{
		require_once "/home/steelmin/public_html/inc/config1.php"; 
		require_once "/home/steelmin/public_html/hf.php"; 
		$query  = "	select distinct message_id 
						from tbl_sms_dlr 
						where status='AWAITED-DLR' 
						and TIMESTAMPDIFF(SECOND, concat(date, ' ', time), NOW()) > 1800";
		 $res = mysql_query($query);
		 if(mysql_num_rows($res)>0)
		 {
		   while($row=mysql_fetch_array($res))
		   {
			  //echo $row['message_id'] ."<br />";
			  fetch_update_dlr($row['message_id'],'GROUP');
		   }
		 }
		 require_once "/home/steelmin/public_html/inc/desconfig.php"; 
		
	}
	
	if( strpos($currTime, '12:02:') !== false ) 
	{
		require('simple_html_dom.php');
		$msgs =file_get_html("https://www.steelmint.com/global_steel_alerts.php");		
	} 
	
	if( strpos($currTime, '09:45:') !== false || (strpos($currTime, '10:30:') !== false && "Mon" != $dayOfWeek) || ("Mon" == $dayOfWeek && strpos($currTime, '11:30:') !== false))
	{ 
		require_once "/home/steelmin/public_html/inc/config1.php"; 
		include_once "/home/steelmin/public_html/cf.php";
		//ini_set('display_errors',1);
		ini_set('memory_limit', '-1');
		include_once("/home/steelmin/public_html/mpdf/mpdf.php");
		$mpdf=new mPDF('c','COAL_NEWS_LETTER','','' , 5 , 5 , 10 , 5 , 0 , 0); 

		$mpdf->mirrorMargins = 1;

		$currDate=date('d M Y');
		$mpdf->SetDisplayMode('default');
		$mpdf->useOddEven = false;
		 $mpdf->SetHTMLFooter('<table style="vertical-align: bottom; font-family: serif; font-size: 8pt; color: #000;padding:2px 10px; font-weight: bold; font-style: italic;" width="100%">
				<tbody>
					<tr>
						<td width="33%"><span style="font-weight: bold; font-style: italic;">Daily News Letter as on '.$currDate.'</span></td>
						<td style="font-weight: bold; font-style: italic;" align="center" width="33%">{PAGENO}/{nbpg}</td>
						<td style="text-align: right;" width="33%"><div style="text-align: right;"><a href="https://www.coalmint.com" target="_blank" style="color: rgb(17, 85, 204);"><img src="https://www.coalmint.com/assets/img/logo.png" width="100px"/></a></div></td>
					</tr>
				</tbody>
			</table>');
		$stylesheet_app = file_get_contents('https://www.steelmint.com/assets/plugins/bootstrap/css/bootstrap.css');
		$mpdf->WriteHTML($stylesheet_app,1);
		$mpdf->WriteHTML('

		.news_letter{font-size: 15px;}	

		table{width:100%}
		.table, .tablesorter{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}
		.table thead tr th, .tablesorter thead tr th{
			  border-bottom: none;
			  background: #eee;color:#333;
			}
		.table thead > tr > th, .tablesorter thead > tr > th {
			background: #eee none repeat scroll 0 0;color:#333;
		}
		.table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td {
			border: 1px solid #ddd;
		}
		.tablesorter > thead > tr > th, .tablesorter > tbody > tr > th, .tablesorter > tfoot > tr > th, .tablesorter > thead > tr > td, .tablesorter > tbody > tr > td, .tablesorter > tfoot > tr > td {
			border: 1px solid #ddd;
		}
		.tablesorter th, .tablesorter td, .tablesorter th, .tablesorter td {
			border: 1px solid #ddd !important;padding:7px;
		}.headerstyle{
		font-weight:bold; background-color:#dedede;	color:#FFFfff;	text-align:left;padding:5px;line-height:18px;
		}
		.belowTbl{color: #888;}
		a {
			color: #e74c3c;
		}
		',1);	

		$content=file_get_contents("https://www.coalmint.com/cm_daily_news_letter.php");

		$mpdf->WriteHTML($content);
		//$mpdf->WriteHTML('<pagebreak resetpagenum="4" />');////table of content page
		//$mpdf->Output("CoalMint Daily News Letter as on ".date("d M Y").".pdf", 'D');
		//echo "CoalMint Daily News Letter as on ".date("d M Y").".pdf"; 
		//die;
		$mpdf->Output("/home/steelmin/public_html/coalmint/cm_daily_news_letter/CoalMint Daily News Letter as on ".(date("d M Y")).".pdf");

		$attachment="coalmint/cm_daily_news_letter/CoalMint Daily News Letter as on ".(date("d M Y")).".pdf";
		$attachment = "/home/steelmin/public_html/".$attachment;
		 
		$msgs='<table align="center" border="0" cellpadding="0" cellspacing="0" width="680">
									<tbody>
									<tr>
										 <td style="font-size:13px;color:#272727;line-height:25px;font-family:Arial,Helvetica,sans-serif">
											Dear Patron <br> <br> Greetings! <br><br>As our valued subscriber, we are happy to offer you a comprehensive Daily Coal Newsletter as on '. date("d, M, Y",strtotime($currDateTime)) .'. <br><br><strong> Please find the full report attached with this e-mail in PDF.  </strong> <br>  
											The Report includes:
											<strong>
											<ul>
												<li> Latest Coal Prices - Coking, Non-coking, Pet coke &amp; Anthracite</li>
												<li> News Updates from Indian and International Coal Markets</li>
												<li> Latest Coal Tender Information </li>
												<li> Weekly Coal Stock at Indian Ports </li>
												<li> Vessel Line-up at Indian Ports </li>
												<li> Bulk Vessel Freight Updates </li>
											</ul>
											</strong>
											<br/>
											<font color="#5f7dde"> <strong>For any queries or discussions</strong> please feel free to write to us at&nbsp;<a href="mailto:info@coalmint.com" style="text-decoration:none;color:blue;font-size:14px"> info@coalmint.com </a>
											<br> 
											Alternatively, for <strong>Subscription details</strong> or queries you can also <font style="text-decoration:none;color:blue;font-size:14px">call on +91-7044070530 </font>
											</font>
										</td>
									</tr>
									<tr>
										<td> 
											<table align="left" border="0" cellpadding="0" cellspacing="0">
												<tbody><tr>
													<td style="font-size:15px;color:#272727;font-weight:light;text-align:center;font-family:Arial,Helvetica,sans-serif;line-height:25px;vertical-align:middle;padding:10px 0px 10px 0px">
														<a href="https://www.coalmint.com/coalnews" style="text-decoration: underline;font-weight: bold;color:#3b3b3b" target="_blank">Coal News</a>
														&nbsp; &nbsp; <a href="https://www.coalmint.com/reports" style="text-decoration: underline;font-weight: bold;color:#3b3b3b" target="_blank">Reports&nbsp;</a>
														&nbsp; &nbsp;
														<a href="https://www.coalmint.com/aboutus" style="text-decoration: underline;font-weight: bold;color:#3b3b3b" target="_blank">About CoalMint</a>
														&nbsp; &nbsp;
														<a href="https://www.coalmint.com/memberegi" style="text-decoration: underline;font-weight: bold;color:#3b3b3b" target="_blank">  Subscription Details </a>  
														 &nbsp; &nbsp;
														<a href="#0.1_" style="text-decoration: underline;font-weight: bold;color:#3b3b3b"> My Account </a>  
														 &nbsp; &nbsp; <a href="https://www.coalmint.com/contact" style="text-decoration: underline;font-weight: bold;color:#3b3b3b" target="_blank">Contact Us </a>  &nbsp; &nbsp;                     
													</td>
												</tr>
											</tbody></table>
										</td>
									</tr>
								</tbody></table>';
		
		//$emails.=',mohan@steelmint.com,rohan@steelmint.com';
		if( strpos($currTime, '09:45:') !== false){ 
			$emails='dhruv@steelmint.com,rohan@steelmint.com';
			$sample_text =' - Sample';
		}else{
			$sample_text='';
			$sql2 =
				"
					SELECT CASE
					 WHEN send_email_to = 'R' THEN email
					 ELSE addtnl_email
					END as email
					from tbl_members
					where id in 
					(
					select distinct memid
					from tbl_reg_logs
					where status = 'Active'
					and f_product In ('C', 'W')
					)
					and verified = 1
					and email_dnd = 0;
				";

			$emails = qryToCommaSepString($sql2); 
		}
		$emails.=',mohan@steelmint.com';
		sendAdminMailer($msgs, $_mail_to=$emails, $name='', $subject="CoalMint Daily News Letter as on ".date("d M Y") .$sample_text, $attachment, $from_email="support@coalmint.com", $from_name="CoalMint", $reply_to="support@coalmint.com");
		require_once "/home/steelmin/public_html/inc/desconfig.php"; 
	} 
	
	if (strpos($currTime, '06:00') !== false || strpos($currTime, '09:00') !== false )
	{
		require_once('/home/steelmin/public_html/steel360/config1.php');
		require_once('/home/steelmin/public_html/steeladmin/hf_360.php');
		require_once('/home/steelmin/public_html/hf.php');
		require_once('/home/steelmin/public_html/mf.php');
	}	
	else
	{
		require_once('/home/steelmin/public_html/inc/config1.php');
		require_once("/home/steelmin/public_html/hf.php");
	}
	if (strpos($currTime, '10:12:') !== false)
	{
		lowerCaseAllEmails();
		require_once("/home/steelmin/public_html/mf.php");
		sendTenderReminders();
		require_once('/home/steelmin/public_html/inc/desconfig.php');
	}	
	
	function lowerCaseAllEmails(){
		mysql_query("
			update tbl_members
			set email = lower(email),
				addtnl_email = lower(addtnl_email),
				username = lower(username);
		");
		mysql_query("UPDATE `tbl_email_gateway_mapping` SET email = lower( email ) ");
	}
	
/* 	if (strpos($currTime, '16:12:') !== false)
	{
		mysql_query("insert into comments (com_dis) value('inide')");
		$expiringMemids = qryToCommaSepString(
			"select memid
			from tbl_reg_logs
			where enddate <= '" . date('Y-m-22') . "'
				AND f_product IN ( 'M' )
				AND status = 'Active'
				and pymDtls = 'Complementary'
		");
		mysql_query("insert into comments (com_dis) value('inide: $expiringMemids')");
		$ex = explode(",", $expiringMemids); $finStr = '';
		for( $i = 0; $i < count($ex); $i++ ){
				$finStr .= "<a href = 'https://www.steelmint.com/steeladmin/magazine_member.php?id=" . $ex[$i] . "'>" . $ex[$i] . "</a>, ";
		}
		mysql_query("insert into comments (com_dis) value('inide2: $finStr')");
		$content = "
			Complementary logs of following memids are expiring today: <br />
			$finStr
		";
		$content = htmlentities($content, ENT_QUOTES);
		mysql_query("insert into comments (com_dis) value('$content')");
		sendSMMail($content, "tarun@steelmint.com", '', "Steel360: Complementary logs expirign today!!");
	}	
	 */
	//mysql_query("insert into tbl_try(f_data) values('startdddd$currTime')");
	function sendTenderReminders()
	{
		 $date = date('Y-m-d');
		 $newdate = strtotime ( '-1 days' , strtotime ( $date ) ) ;
		 $newdate = date ( 'Y-m-d' , $newdate );
		 $dt_cond = " (opening_date like '". $newdate . "%' or (opening_date = '0000-00-00 00:00:00' and due_date like '".$newdate. "%')) ";
		 $res=mysql_query("select distinct sub_category from tbl_tenders ");
		 while($row=mysql_fetch_array($res))
			 $cat[]=$row['sub_category'];
		 
		$finMail = '';
		 foreach($cat as $val)
		 {
			$t='Hi, <br><br><table border="1" cellpadding="5" cellspacing="0" style="border:1px solid">
					<caption style="font-weight:bold;">Expired Tender Details</caption>
					<tr>
					<th>Company Name</th>
					<th>Product</th>
					<th>Quantity</th>
					<th>Due Date</th>
					<th>Opening Date</th>
					<th>Buy/Sell</th>
					</tr>';
			$eml=mysql_fetch_array(mysql_query("select * from tbl_concerned_email_id where (product like '%,".$val."' or product like '".$val.",%' or product like '%".$val."%' or product like '%,".$val.",%')"));
			
			//$to=$eml['to'].','.$eml['cc'];
			$to = $eml['to'];
			$q=mysql_query("select * from tbl_tenders where ".$dt_cond." and sub_category='$val'");
			 if(mysql_num_rows($q)>0){
				  while($r=mysql_fetch_array($q))
				  {
					$t.='<tr>
							<td>'.$r['company_name'].'</td>
							<td><a href="https://www.steelmint.com/tenders?&tende_type=archive&cat='.$val.'&tag='.$val.'">'.$r['sub_category'].'</a></td>
							<td>'.$r['qty'].'</td>
							<td>'.$r['due_date'].'</td>
							<td>'.$r['opening_date'].'</td>					
							<td>'.$r['buy_sell'].'</td>					
							</tr>';
				  }
				  $t.='</table><br><br><strong>Please keep track for result</strong>';
				$finMail .= $t . "<br /><br /><br />";
				sendSMMail($msgs=$t, $email=$to, $name="", $subject="SteelMint Expired Tenders Alert: $val", $attachment="", $from_email="info@steelmint.com", $from_name="Expired Tenders", $reply_to="info@steelmint.com");
			  }
		 }	
		sendSMMail($finMail, "parul@steelmint.com,dhruv@steelmint.com,anurag.gupta@steelmint.com", $name="", $subject="SteelMint Expired Tenders Alerts", $attachment="", $from_email="info@steelmint.com", $from_name="Expired Tenders", $reply_to="info@steelmint.com");
	}
	if (strpos($currTime, '13:40:') !== false || strpos($currTime, '16:00:') !== false  || strpos($currTime, '17:34:') !== false)
	{
		require_once("/home/steelmin/public_html/mf.php");
		$query = mysql_query("select * from tbl_webhooks where 1");
		$blacklistedEmailIds = '';
		
		while ($row = mysql_fetch_array($query))
		{
			$ins_query = "";
			$message_id = '';
			$status = '';
			$email = '';
			$unserialized_data = '';
			$data_array = array();
			$j = 0;
			$i = 0;
			if ($row['f_gateway_name'] == 'MANDRILL')
			{
				$unserialized_data = unserialize(base64_decode($row['f_data']));
				$data = json_decode($unserialized_data['mandrill_events']);
				if (count($data) > 0)
				{
					foreach($data as $d)
					{
						$data_array[$i]['message_id'] = $d->_id;
						$data_array[$i]['email'] = $d->msg->email;
						$data_array[$i]['status'] = "Undelivered";
						if (trim($d->event) == 'delivered' || trim($d->event) == 'send')
						{
							$data_array[$i]['status'] = 'delivered';
						}
						$i++;
					}
				}
			}
			elseif ($row['f_gateway_name'] == 'MAILGUN')
			{
				$data = unserialize(base64_decode($row['f_data']));
				$data_array[0]['message_id'] = $data['Message-Id'];		
				$data_array[0]['email']  = $data['recipient'];
				$data_array[0]['status'] = "Undelivered";
				if (trim($data['event']) == 'delivered')
					$data_array[0]['status']  = 'delivered';
			}
			elseif ($row['f_gateway_name'] == 'SENDGRID')
			{
				$data = json_decode($row['f_data']);
				if (count($data) > 0)
				{
					foreach($data as $d)
					{
						$data_array[$i]['message_id'] = $d->msgId;
						$data_array[$i]['email'] = $d->email;
						$data_array[$i]['status'] = "Undelivered";
						if (trim($d->event) == 'delivered')
							$data_array[$i]['status'] = 'delivered';
						$i++;
					}
				}
			}
			elseif ($row['f_gateway_name'] == 'SARV')
			{
				$unserialized_data = unserialize(base64_decode($row['f_data']));
				$data = json_decode($unserialized_data['sarvtes_events']);
				if (count($data) > 0)
				{
					foreach($data as $d)
					{
						if (trim($d->event) == 'delivered')
						{
							$ins_query = "
								update tbl_delivery_status 
								set status = 'delivered'
								where message_id = '" . $d -> x_unique_id . "'"
							;
							mysql_query($ins_query);
						} else if (trim($d->event) == 'soft_bounce' || trim($d->event) == 'hard_bounce' || trim($d->event) == 'spam'){							if('' != $d->email)							mysql_query('insert into tbl_email_gateway_mapping (email, gateway_name, gateway_status, earlier_gateway)							values ("' . $d->email . '", "FAKE", "THRU SARV", "crongeneral-' .date('Y-m-d H:i:s') . '")');						}
					}
				}
			}
		
			if (count($data_array) > 0)
			{
				foreach($data_array as $final_data)
				{
					$message_id = $final_data['message_id'];
					$status = $final_data['status'];
					$email = $final_data['email'];
					if(trim($message_id) != '' && trim($email)!='')
					{
						   $r = mysql_query("
											select * 
											from tbl_mailer_info 
											where Match(f_recipient_email) AGAINST ('\"$email\"' IN BOOLEAN MODE)
											and  (
												message_id1 like '%$message_id%' 
												OR message_id2 like '%$message_id%' 
												OR message_id3= '$message_id'
											)
										");
						if (mysql_num_rows($r) > 0)
						{
							$mailer_info_data = mysql_fetch_array($r);
                                                        $chk_rcd = mysql_query("select id from tbl_delivery_status where mailer_info_id= '" . $mailer_info_data['id'] . "' and email='$email' and message_id='$message_id' ");
                                                        if(mysql_num_rows($chk_rcd)==0){
							$ins_query = "insert into tbl_delivery_status (webhook_id,mailer_info_id,email,status,message_id,gateway_name,f_date_scheduled) values('" . $row['id'] . "', '" . $mailer_info_data['id'] . "','$email','$status','$message_id','" . $row['f_gateway_name'] . "', '$currDateTime')";
							if (mysql_query($ins_query))
							{
								$j++;
								// updated tbl_email_gateway_mapping for delivered status
								if (trim($status) == 'delivered') mysql_query( "update tbl_email_gateway_mapping set gateway_status='done' where email='$email' ");
								else
								{
									$gateway_name = qryToCommaSepString("select gateway_name from tbl_email_gateway_mapping where email= '$email' ");
									if ($gateway_name == 'MAILGUN'){
										if ($gateway_name == $row['f_gateway_name'])
											mysql_query( "update tbl_email_gateway_mapping set gateway_name ='blacklisted' ,gateway_status='' where email='$email' ");
									} else {
										$next_gateway = '';
		
										// assign next gateway
										//if ($gateway_name == 'MANDRILL') $next_gateway = 'MAILGUN';
										//if ($gateway_name == 'MAILGUN') $next_gateway = 'SPARKPOST';
										if ($next_gateway != '')
										{
											// set next gateway in tbl_email_gateway_mapping
											$up_query = "update tbl_email_gateway_mapping set gateway_name ='$next_gateway'  where email='$email' ";
											if ($gateway_name == $row['f_gateway_name'])
												mysql_query( $up_query);
		
											// resend Email With Parent id
											if ($mailer_info_data['parent_id'] != 0) $parent = $mailer_info_data['parent_id'];
											else $parent = $mailer_info_data['id'];
											//echo "Resend Mail : $email parent : $parent";
											//print_r($mailer_info_data);
											sendSMMail(html_entity_decode($mailer_info_data['f_body_txt'], ENT_QUOTES) , $email, $name = "", html_entity_decode($mailer_info_data['f_subject'], ENT_QUOTES) , $mailer_info_data['f_attachments'], $mailer_info_data['f_sender_id'], html_entity_decode($mailer_info_data['f_sender_name'], ENT_QUOTES) , $reply_to = $mailer_info_data['f_sender_id'], $recipient_variables = '', $parent);
											
										}
									}
								}
							}
                                                   }
						}
					  }
				}
		
				//if (count($data_array) == $j) 
		//		echo "<br />delete from tbl_webhooks where id = " . $row['id'];
				mysql_query("delete from tbl_webhooks where id = " . $row['id']);
			}
		}
		/* if( strpos($currTime, '19:00') !== false){
			$blacklistedEmailIds = qryToCommaSepString("select distinct email from tbl_email_gateway_mapping where gateway_name= 'blacklisted' ");
			sendSMMail("Following emails are not receiving emails from either of email gateways: <br />" . $blacklistedEmailIds, "info@steelmint.com", "", "Emails facing delivery issue", "", "info@steelmint.com", "Steelmint", "info@steelmint.com");
		} */ 
		require_once('/home/steelmin/public_html/inc/desconfig.php');
	}
	
//***********
	if (strpos($currTime, '14:00') !== false || strpos($currTime, '09:10') !== false || strpos($currTime, '23:00') !== false || strpos($currTime, '19:33') !== false)
	{
		require_once(dirname( __FILE__ ) . '/inc/config1.php');
		require_once(dirname( __FILE__ ) . '/cf.php');
		require_once(dirname( __FILE__ ) . '/hf.php');

		update_inv_tbl();
		
		//create log in tbl_updated_reg_logs for memids whose log doesnt not exist is this table but has W/S srvc in tbl_reg_logs.
		createMissingLogsInUpdatedRegLogTbl();
		
		//mysql_query("insert into tbl_try(f_data) values('tar1')");
		$res = mysql_query("
			SELECT distinct a.memid as memid 
			FROM `tbl_reg_logs` a 
			join tbl_updated_reg_logs b 
			ON a.memid=b.memid 
			and a.f_product = b.services 
			where a.status!= b.status 
			and a.status='active' 
			and a.selected_products <> 'NEWS' 
			and (a.f_product='W'  OR a.f_product = 'S')
		");
		//$memid = array();
		while($result = mysql_fetch_array($res))		{
			//$memid[] = $result['memid'];
			updateTbltbl_updated_reg_logs($result['memid'], 'Y');
		}
		//mysql_query("insert into tbl_try(f_data) values('tar2')");
		//if(!empty($memid)){
			//$final_memid = implode(",",$memid);
			//updateTbltbl_updated_reg_logs($final_memid);
		//}
		//mysql_query("insert into tbl_try(f_data) values('tar3')");
		//*******************update email_category in records whose srvc is active but email_category = ''		
		 $query = mysql_query("
		SELECT DISTINCT mem.id AS memid, mem.username AS email, reg.f_tenure, reg.selected_products, datediff( reg.enddate, reg.startdate )
		FROM tbl_members AS mem, tbl_reg_logs AS reg
		WHERE mem.id = reg.memid
		AND reg.status = 'Active'
		AND reg.f_product = 'W'
		AND mem.email_category = ''
		");
		//mysql_query("insert into tbl_try(f_data) values('tar4')");
		if(mysql_num_rows($query)>0)
		{
		  while($row = mysql_fetch_array($query))
		  {
			$fTenure = $row['f_tenure'];
			$selectedProducts = $row['selected_products'];
			
			
			if( $fTenure == 'Free Trial' ){
				$srvc = "Free Trial";
			} else {
				if( strpos($selectedProducts, "VAS-G") !== false ){
					$srvc = "VAS-G";
				} elseif( strpos($selectedProducts, "VAS-P") !== false ) {
					if(allowAccessToDownloaddataInEXCEL($row['email'])){
						$srvc = "VAS-P + XLS";
					} else {
						$srvc = "VAS-P";
					}
				} else {
					$srvc = $row['selected_products'];
				}
			}
			$srvc = trim($srvc , ",");
			//mysql_query("insert into tbl_try(f_data) values('tar5$srvc')");
			if( "FinishLong" == $srvc )
			   sub_unsub_email_prefrence($row['memid'], 'subscribe', "", '', $srvc,'');
			 else  
			 sub_unsub_email_prefrence($row['memid'], 'subscribe', $srvc, '', '','');
			 //mysql_query("insert into tbl_try(f_data) values('tar6$srvc')");
		  }
		}
		//mysql_query("insert into tbl_try(f_data) values('tar7')");
	}
//***********	
	//generate manualy created invoice
	/* if( strpos($currTime, '18:36:') !== false ){
		//mysql_query("insert into tbl_try(f_data) values('start$currTime')");
		UpdateInvoiceLog();
	} */
	
	if( strpos($currTime, '16:00:') !== false && "Sun" != $dayOfWeek && "2016-08-18" != date("Y-m-d") ) 
	{
		/* include_once "cf.php";
		include_once "cf_new.php";
		include_once "mf.php";
		
		//$msgs = getDailyReportPrices($item='INGOT', $category='', $show_remark=true, $titlePrifix='', $firstcolName='Place', $ldate='', $rowsToShow='*', $at_place='daily_report', $type='DOM', $date='', $other_cond='', $cond_type='', $order_by='', $jsMorePlaces, $on_report='yes', $is_header=false);
		
		$msgs = getDailyReportPrices_new($item='', $_index_id='136,137,138,139,140,141', $at_place='indian_steel_trade', $other_cond='', $is_header=false);*/
		///no need to send sample mail by manish 
		require_once "inc/config1.php"; 
		include_once "cf.php";
		include_once "hf.php";
		include_once "cf_new.php";
		
		$attachment = getIndianSteelTradeAttachment();
		$attachment = "/home/steelmin/public_html/".$attachment;
		
		$str='<div style="font-family: verdana;"><strong>Dear Patron,</strong></div>';
		$str.='<p><em>Greetings from SteelMint..!!</em></p>';
			 
		$str.='<p>Prices (in INR/MT) as on '. date('l, d M Y', strtotime($GLOBALS['currDateTime'])) .'</p>';
		
		//$msgs=file_get_contents("https://www.steelmint.com/indian_steel_prices.php");
		require('simple_html_dom.php');
		$msgs =file_get_html("https://www.steelmint.com/indian_steel_prices.php");
		$content = $msgs->find('div[class="report_second"]')[0];
		
		require_once 'inlinecss/CssToInlineStyles.php';
		$cssToInlineStyles = new CssToInlineStyles();
		$cssToInlineStyles->setHTML($content);
		$cssToInlineStyles->setCSS('table{width:100%}
							.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}
							.table thead tr th {
							  border-bottom: none;
							  background: #eee;
							}
						.table thead > tr > th {
							background: #eee none repeat scroll 0 0;
						}
						.table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td {
							border: 1px solid #ddd;
						}
						.table-bordered th, .table-bordered td {
							border: 1px solid #ddd !important;padding:7px;
						}');
		// output 
		$content = $cssToInlineStyles->convert();
			
		$msgs = $str.$content;
		
		sendSMMail($msgs, "sumit@steelmint.com,manish@steelmint.com", "", "India Steel Trade - Sample", $attachment, "info@steelmint.com", "SteelMint", "info@steelmint.com");
		
		require_once('inc/desconfig.php'); 
	} 
	 
	if( strpos($currTime, '17:00:') !== false && "Sun" != $dayOfWeek && "2016-08-18" != date("Y-m-d") )
	{
		/* include_once "cf.php";
		include_once "mf.php";
		include_once "hf.php";
		include_once "cf_new.php"; */
		require_once "inc/config1.php"; 
		include_once "cf.php";
		include_once "hf.php";
		include_once "cf_new.php";
		
		$attachment = getIndianSteelTradeAttachment();
		$attachment = "/home/steelmin/public_html/".$attachment;
		
		$str='<div style="font-family: verdana;"><strong>Dear Patron,</strong></div>';
		$str.='<p><em>Greetings from SteelMint..!!</em></p>';
			 
		$str.='<p>Prices (in INR/MT) as on '. date('l, d M Y', strtotime($GLOBALS['currDateTime'])) .'</p>';
		$str.='<p>Please find the attached PDF file of conversion spread.</p>';
		
		//$msgs=file_get_contents("https://www.steelmint.com/indian_steel_prices.php");
		require('simple_html_dom.php');
		$msgs =file_get_html("https://www.steelmint.com/indian_steel_prices.php");
		$content = $msgs->find('div[class="report_second"]')[0];
		
		require_once 'inlinecss/CssToInlineStyles.php';
		$cssToInlineStyles = new CssToInlineStyles();
		$cssToInlineStyles->setHTML($content);
		$cssToInlineStyles->setCSS('table{width:100%}
							.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}
							.table thead tr th {
							  border-bottom: none;
							  background: #eee;
							}
						.table thead > tr > th {
							background: #eee none repeat scroll 0 0;
						}
						.table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td {
							border: 1px solid #ddd;
						}
						.table-bordered th, .table-bordered td {
							border: 1px solid #ddd !important;padding:7px;
						}');
		// output 
		$content = $cssToInlineStyles->convert();
			
		$msgs = $str.$content;
		
		$emails_rs = qryToCommaSepString("
			select 
				CASE
					when send_email_to = 'A' then addtnl_email
					else email
				END
			as emails
			from tbl_members
			where `email_category` like '%17%'
			and verified = 1
			and email_dnd = 0
		");
		
		//$msgs = getDailyReportPrices($item='INGOT', $category='', $show_remark=true, $titlePrifix='', //$firstcolName='Place', $ldate='', $rowsToShow='*', $at_place='daily_report', $type='DOM', $date='', //$other_cond='', $cond_type='', $order_by='', $jsMorePlaces, $on_report='yes', $is_header=false);
		
		////////$msgs = getDailyReportPrices_new($item='', $_index_id='136,137,138,139,140,141', $at_place='indian_steel_trade', $other_cond='', $is_header=false);
		//jharkhandsponge@gmail.com addead as an special case as per sumit's email dated 31-3-2016
		$r = sendAdminMailer($msgs, $emails_rs, "", "India Steel Trade", $attachment, "info@steelmint.com", "SteelMint", "info@steelmint.com");
	} 
	////Global Steel Trade
	if( strpos($currTime, '08:00:') !== false && "Mon" == $dayOfWeek)
	{
		require_once "/home/steelmin/public_html/inc/config1.php"; 	
		
		$filename = '/home/steelmin/public_html/daily_report/global_prices_report_output.php';
		if (file_exists($filename)) {
			//if report not generated on sat last week
			if(date("Y-m-d", filemtime($filename))!=date("Y-m-d",strtotime($currDateTime . '-2 days')))
			{
				require_once "/home/steelmin/public_html/inc/config1.php"; 	
				//ini_set('display_errors',1);
				require_once "/home/steelmin/public_html/mf.php"; 


				$msgs=' <a href="https://www.steelmint.com/daily_report/global_prices_report.php">Click here</a> to send Global Steel Trade Mailer';
				//echo $msgs;

				sendSMMail($msgs, 'mohan@steelmint.com,tarun@steelmint.com', $name='', $subject="SteelMint : Global Steel Prices not Generated on last saturday or its older");
				//include "inc/desconfig.php";	
				require_once('/home/steelmin/public_html/inc/desconfig.php');
			}else{
				
				//ini_set('display_errors',1);
				require_once "/home/steelmin/public_html/hf.php"; 
				require_once "/home/steelmin/public_html/mf.php"; 
				//$last_date = $currDate;
				$last_date = date("Y-m-d",strtotime($currDateTime . '-1 weeks'));
				
				$sql_qry = "SELECT * FROM `tbl_year_week` where '$last_date'>=monday and '$last_date' <= sunday";
				$rs_weeks = mysql_query($sql_qry) or die(mysql_error());
				$row = mysql_fetch_array($rs_weeks,MYSQL_ASSOC);
				
				$as_on_date_text = ' Week '. $row['week'].', '. $row['year'] .' ( '. date("d M", strtotime($row['monday'])).' - '. date('d M',strtotime($row['sunday'])).' )';
				
				//$last_week_date = date("W M Y",strtotime($currDateTime . '-1 weeks'));
				$subject="SteelMint : Global Steel Trade - " . $as_on_date_text;
				
				$msgs=file_get_contents("https://www.steelmint.com/daily_report/global_prices_report_output.php");
				//echo $msgs;
				$sql2 =
					"
						SELECT CASE
						 WHEN send_email_to = 'R' THEN email
						 ELSE addtnl_email
						END as email
						from tbl_members
						where id in 
						(
						select distinct memid
						from tbl_reg_logs
						where status = 'Active'
						and f_product = 'W'
						)
						and verified = 1
						and email_dnd = 0;
					";

				$emails = qryToCommaSepString($sql2);  
				
				///sending sample to 
				sendAdminMailer($msgs, $_mail_to=$emails, $name='', $subject, $attachment='', $from_email="info@steelmint.com", $from_name="SteelMint", $reply_to="info@steelmint.com");
				//sendSMMail($msgs, $emails='mohan@steelmint.com', $cc_name='', $subject, $attachment='', $from_email="info@steelmint.com", $from_name="SteelMint", $reply_to="info@steelmint.com");
				//include "inc/desconfig.php";	
				require_once('/home/steelmin/public_html/inc/desconfig.php');
			}			
		}
		
	}
	
	////market tracker
	if( strpos($currTime, '12:15:') !== false && "Mon" == $dayOfWeek)
	{
		require_once "/home/steelmin/public_html/inc/config1.php"; 
		include_once "/home/steelmin/public_html/cf.php";
		//ini_set('display_errors',1); 
		include_once("/home/steelmin/public_html/mpdf/mpdf.php");
		$mpdf=new mPDF('c','MT','','' , 5 , 5 , 5 , 5 , 0 , 0); 

		//$mpdf->SetWatermarkText('SteelMint');
		//$mpdf->watermark_font = 'DejaVuSansCondensed';
		//$mpdf->showWatermarkText = true;

		$mpdf->mirrorMargins = 1;

		$mpdf->SetDisplayMode('default');

		$mpdf->SetWatermarkImage('https://www.steelmint.com/images/logo_large.png', 0.15, 'D');
		$mpdf->showWatermarkImage = true;
		//$stylesheet_app = file_get_contents('https://www.steelmint.com/assets/plugins/bootstrap/css/bootstrap.css');
		$mpdf->WriteHTML('table{width:100%}
									.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}
									.table thead tr th {
									  border-bottom: none;
									  background: #1c7094;
									}
								.table thead > tr > th {
									background: #1c7094 none repeat scroll 0 0;
								}
								.table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td {
									border: 1px solid #ddd;
								}
								.table-bordered th, .table-bordered td {
									border: 1px solid #ddd !important;padding:7px;
								}.headerstyle{
			font-weight:bold; background-color:#1c7094;	color:#FFFfff;	text-align:left;padding:5px;line-height:18px;
		}',1);	

		$content=file_get_contents("https://www.steelmint.com/market_tracker.php");
			
		$mpdf->WriteHTML($content);
		//$mpdf->WriteHTML('<pagebreak resetpagenum="4" />');////table of content page
		//$mpdf->Output("SteelMintint daily report as on ".date("d M Y").".pdf", 'D');
		$mpdf->Output("/home/steelmin/public_html/files_market_tracker/SteelMint Market Tracker as on Week ".(date('W')-1). "-". date('Y') .".pdf");

		$attachment="files_market_tracker/SteelMint Market Tracker as on Week ".(date('W')-1). "-". date('Y') .".pdf";
		$attachment = "/home/steelmin/public_html/".$attachment;

		$last_date = date("Y-m-d",strtotime($currDateTime . '-1 weeks'));
				
		$sql_qry = "SELECT * FROM `tbl_year_week` where '$last_date'>=monday and '$last_date' <= sunday";
		$rs_weeks = mysql_query($sql_qry) or die(mysql_error());
		$row = mysql_fetch_array($rs_weeks,MYSQL_ASSOC);

		$as_on_date_text = ' Week '. $row['week'].', '. $row['year'] .' ( '. date("d M", strtotime($row['monday'])).' - '. date('d M',strtotime($row['sunday'])).' )';

		$msgs='<div style="color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 13px; background-color: rgb(255, 255, 255);">Dear Patron,</div><div style="color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 13px; background-color: rgb(255, 255, 255);"><br></div><div style="color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 13px; background-color: rgb(255, 255, 255);">Greetings from SteelMint!!</div><span style="font-family: arial, sans-serif; color: rgb(80, 0, 80); font-size: 13px; background-color: rgb(255, 255, 255);"><div style="color: rgb(34, 34, 34);"><br></div><div style="color: rgb(34, 34, 34);">As our valued subscriber, we are happy to offer you with a comprehensive&nbsp;<span class="il">Market</span>&nbsp;<span class="il">Tracker</span>&nbsp;as updated on '.$as_on_date_text.'<br></div><div style="color: rgb(34, 34, 34);"><br></div><div style="color: rgb(34, 34, 34);"><b>Report features:</b></div><div style="color: rgb(34, 34, 34);"><br></div></span><div style="font-family: arial, sans-serif; color: rgb(80, 0, 80); font-size: 13px; background-color: rgb(255, 255, 255);"><ul style="color: rgb(34, 34, 34);"><li style="margin-left: 15px;">It provides domestic &amp; international prices of various Steel products - from raw material to finished products; covering major&nbsp;<span class="il">market</span></li></ul><ul style="color: rgb(34, 34, 34);"><li style="margin-left: 15px;">The reference data of 3 months before is also available<span style="font-size: small;"></span></li></ul><p style="color: rgb(34, 34, 34);"><br></p><p><font color="#222222">Please download the PDF report attached with this e-mail.&nbsp;</font><br><br><font color="#222222">For any queries or discussions please write to me on&nbsp;</font><font color="#0099ff"><a href="mailto:info@steelmint.com" target="_blank" style="color: rgb(17, 85, 204);">info@steelmint.com</a></font></p></div>';

		//echo $msgs;
		$sql2 =
			"
				SELECT CASE
				 WHEN send_email_to = 'R' THEN email
				 ELSE addtnl_email
				END as email
				from tbl_members
				where id in 
				(
				select distinct memid
				from tbl_reg_logs
				where status = 'Active'
				and f_product = 'W'
				)
				and verified = 1
				and email_dnd = 0;
			";

		$emails = qryToCommaSepString($sql2);  
		
		///sending sample to 
		sendAdminMailer($msgs, $_mail_to=$emails, $name='', $subject="SteelMint Market Tracker as on ".$as_on_date_text, $attachment, $from_email="info@steelmint.com", $from_name="SteelMint", $reply_to="info@steelmint.com");
		//sendSMMail($msgs, $emails='mohan@steelmint.com', $cc_name='', $subject, $attachment='', $from_email="info@steelmint.com", $from_name="SteelMint", $reply_to="info@steelmint.com");
		//include "inc/desconfig.php";	
		require_once('/home/steelmin/public_html/inc/desconfig.php');
	}
	/*if( strpos($currTime, '16:55:') !== false )
	{
		if(  "Fri" == $dayOfWeek || "Wed" == $dayOfWeek )
		{
			$shanghai = getSHanghaiData();
			$currDate = date('Y-m-d');
			mysql_query("
				insert into tbl_dollar_cme_shanghai_data (f_date_time, type, value)
				VALUES 
				('$currDate', 'SHANGHAI', '$shanghai')
			") or die(mysql_error());	
		}
		
		if( "Sat" == $dayOfWeek || "Wed" == $dayOfWeek )
		{
			$cme      = getCMEData();
			$currDate = date('Y-m-d');
			mysql_query("
				insert into tbl_dollar_cme_shanghai_data (f_date_time, type, value)
				VALUES 
				('$currDate', 'CME', '$cme')
			") or die(mysql_error());	
		}	
		
		update_currencies();
	}

	function update_currencies()
	{
		include('simple_html_dom.php');
		$arr=array(
			array("India (INR)","INR,USD,1,4","https://www.xe.com","USD"),
			array("China (Yuan)","CNY,USD,4,1","https://www.xe.com/?c=CNY","YUAN_IN_USD"),
			array("Brazil (Real)","BRL,USD,4,1","https://www.xe.com/?c=BRL","REAL_IN_USD"),
			array("Australia (Dollar)","AUD,USD,1,5","https://www.xe.com","AUS_IN_USD"),
			array("South Africa (Rand)","ZAR,USD,1,7","https://www.xe.com","RAND_IN_USD"),
			array("United Arab Emirates (Dirham)","AED,USD,4,1","https://www.xe.com/?c=AED","DIRHAM_IN_USD"),
			array("Indonesia (Rupiah)","IDR,USD,4,1","https://www.xe.com/?c=IDR","RUPIAH_IN_USD"),
			array("Europe (Euro)","EUR,USD,1,2","https://www.xe.com","EURO_IN_USD")
		);
		$currDate = date('Y-m-d');
		foreach($arr as $key=>$val){
			$name=$val[0];
			$srch=$val[1];
			$link=$val[2];
			$type=$val[3];
			$value=get_value($link,$srch);
			mysql_query("insert into tbl_dollar_cme_shanghai_data (f_date_time, type, value) VALUES ('$currDate', '$type', '$value')") or die(mysql_error());
		}
	}

	function get_value($link,$srch){
		$html = file_get_html($link);
		$find='a[rel='.$srch.']';
		foreach($html->find($find) as $e)
		 return $e->innertext;
	}*/

	//$dayOfWeek = date( "w", strtotime($currDateTime));
	/*if( ( "Fri" == $dayOfWeek || "Wed" == $dayOfWeek) && strpos($currTime, '16:55:') !== false )
	{
		$shanghai = getSHanghaiData();
		$currDate = date('Y-m-d');
		mysql_query("
			insert into tbl_dollar_cme_shanghai_data (f_date_time, type, value)
			VALUES 
			('$currDate', 'SHANGHAI', '$shanghai')
		") or die(mysql_error());	
	}
	
	if( ( "Sat" == $dayOfWeek || "Wed" == $dayOfWeek) && strpos($currTime, '16:55:') !== false )
	{
		$cme      = getCMEData();
		$usd      = getUSD_to_INRData();
		$currDate = date('Y-m-d');
		mysql_query("
			insert into tbl_dollar_cme_shanghai_data (f_date_time, type, value)
			VALUES 
			('$currDate', 'CME', '$cme'),
			('$currDate', 'USD', '$usd');
		") or die(mysql_error());
	}*/
	/*$sqlquery = mysql_query("SELECT id ,logtime FROM `tbl_members` where logstatus='Active'");
	while($res = mysql_fetch_array($sqlquery)){
		$tlast = $res['logtime'];
		$tback = strtotime($currDateTime) ;
		   if($tlast<$tback){
				   mysql_query("UPDATE `tbl_members` set logstatus='',session='',logtime='' where id='$res[id]'");
		   }
	}*/
	
	/*function delete_same_pattern_tables($delete_table_name_pattern = 'tmpTblMagazineExcelDnld_'){
		echo $sql="
				SHOW TABLES 
				FROM steelmin_steel360 
				where Tables_in_steelmin_steel360 like '%$delete_table_name_pattern%'
			";
			  
		$res=mysql_query($sql);
		if(mysql_num_rows($res)>0){
			while($row=mysql_fetch_array($res)){
				$sql_drop="Drop table ".$row['Tables_in_steelmin_steel360'];
				$res_drop=mysql_query($sql_drop);
			}
		}
		else{
			echo "No Match found";
		}
	}*/
	
	
function update_inv_tbl(){
		//update col inv_cat of tbl_invoice_log
		/*
		tax_evt .. like %Events% and inv_type = 'T'
		pro_evt

		tax_web .. like %Web% and inv_type = 'T'
		tax_sms .. like %Sms% and inv_type = 'T'
		tax_all .. like %All% and inv_type = 'T'

		pro_web .. like %PROFORMA/Web% and inv_type = 'P'
		pro_sms .. like %PROFORMA/Sms% and inv_type = 'P'
		pro_all .. like %PROFORMA/All% and inv_type = 'P'
		*/
		mysql_query("
			update `tbl_invoice_log`
			set `inv_cat` = 'tax_evt'
			WHERE `inv_cat` = '' AND `inv_no` like '%Events%' and inv_type = 'T';
		");
		
		mysql_query("	update `tbl_invoice_log`
			set `inv_cat` = 'tax_web'
			WHERE `inv_cat` = '' AND `inv_no` like '%Web%' and inv_type = 'T';");

		mysql_query("	update `tbl_invoice_log`
			set `inv_cat` = 'tax_sms'
			WHERE `inv_cat` = '' AND `inv_no` like '%Sms%' and inv_type = 'T';");

		mysql_query("	update `tbl_invoice_log`
			set `inv_cat` = 'tax_all'
			WHERE `inv_cat` = '' AND `inv_no` like '%All%' and inv_type = 'T';");

			mysql_query("update `tbl_invoice_log`
			set `inv_cat` = 'pro_web'
			WHERE `inv_cat` = '' AND `inv_no` like '%Web%' and inv_type = 'P';");

			mysql_query("update `tbl_invoice_log`
			set `inv_cat` = 'pro_sms'
			WHERE `inv_cat` = '' AND `inv_no` like '%Sms%' and inv_type = 'P';");

			mysql_query("update `tbl_invoice_log`
			set `inv_cat` = 'pro_all'
			WHERE `inv_cat` = '' AND `inv_no` like '%All%' and inv_type = 'P';");

		mysql_query("	update `tbl_invoice_log`
			set `inv_cat` = 'Mkt_360'
			WHERE `inv_cat` = '' AND `inv_no` like '%ST360%' and inv_type = 'M';");

		mysql_query("	update `tbl_invoice_log`
			set `inv_cat` = 'Mkt_CMM'
			WHERE `inv_cat` = '' AND `inv_no` like '%CM%' and inv_type = 'M';");

		mysql_query("	update `tbl_invoice_log`
			set `inv_cat` = 'Mkt_SMM'
			WHERE `inv_cat` = '' AND `inv_no` like '%SM%' and inv_type = 'M';");

		mysql_query("	update `tbl_invoice_log`
			set `inv_cat` = 'Mkt_EVT'
			WHERE `inv_cat` = '' AND `inv_no` like '%EVT%' and inv_type = 'M';");

		mysql_query("	update `tbl_invoice_log`
			set `inv_cat` = 'Mkt_PBB'
			WHERE `inv_cat` = '' AND `inv_no` like '%PB%' and inv_type = 'M';");
		
	}

	
	function ExtractDataFromComment($str)
	{
		list($inv_date, $cust_type, $order_ref) = explode("/", str_replace("invoice not yet generated ", "", $str));
		$r[] = str_replace("inv_date : ", "", $inv_date);
		$r[] = str_replace("cust_type : ", "", $cust_type);
		$r[]  = str_replace("order_ref : ", "", $order_ref);
		return $r;
	}
	
	/* function UpdateInvoiceLog(){
		
		$inv_array = array();
		$res = mysql_query("select * from  tbl_reg_logs where comments LIKE '%invoice not yet generated inv_date%' and form_no <> 'manual_inv_created' group by inv_no,memid order by inv_no,memid");
		//mysql_query("insert into tbl_try(f_data) values('res: $res')");
		while($row = mysql_fetch_array($res,MYSQL_ASSOC))
			$inv_array[$row['inv_no']][]  = $row;
		//print_r ($inv_array);
		$c = count($inv_array);
		//mysql_query("insert into tbl_try(f_data) values('c: $c')");
		foreach($inv_array as $first_array)
		{
			if(count($first_array)>1){
				$i ='A';
				foreach($first_array as $second)
				{
					//getting rel manager 
					$r =  qryToCommaSepString("select relMngr from tbl_members where id= ".$second['memid']);
					//getting data from comment 
					$data = ExtractDataFromComment($second['comments']);
					if(strpos($second['inv_no'],"PROFORMA")=== false)
						$inv_type = 'T';
					else
					 $inv_type = 'P';
				 
			
					if(mysql_query("insert into tbl_invoice_log (`memid`,`inv_no`,`RelManager`,`buyer_ord_ref`,`inv_type`,`CustType`,`inv_generation_date`,`pymtDtls`,`pymtdate`,`pymtMode`,`smbank`) values('".$second['memid']."','"
					.$second['inv_no']."/".$i."' , '".$r."','".$data[2]."','".$inv_type."','".$data[1]."','".$data[0]."','".$second['pymDtls']."','".$second['datepay']."','".$second['pymtMode']."','".$second['bank_name']."')")){			
						mysql_query("update tbl_reg_logs set inv_no='".$second['inv_no']
					."/".$i ."',form_no='manual_inv_created' where inv_no= '".$second['inv_no']."' and memid = '".$second['memid']."' ");
					}
					updateTbltbl_updated_reg_logs($second['memid']);
					$i++;
				}
			} else	{
				$r =  qryToCommaSepString("select relMngr from tbl_members where id= '".$first_array[0]['memid']. "'");	
				//getting data from comment 
				$data = ExtractDataFromComment($first_array[0]['comments']);
				if(strpos($first_array[0]['inv_no'],"PROFORMA")=== false)
					$inv_type = 'T';
				else
				 $inv_type = 'P';
			
				if(mysql_query("insert into tbl_invoice_log (`memid`,`inv_no`,`RelManager`,`buyer_ord_ref`,`inv_type`,`CustType`,`inv_generation_date`,`pymtDtls`,`pymtdate`,`pymtMode`,`smbank`)  values('".$first_array[0]['memid']."','".$first_array[0]['inv_no']."' ,'".$r."','".$data[2]."','".$inv_type."','".$data[1]."','".$data[0]."','".$first_array[0]['pymDtls']."','".$first_array[0]['datepay']."','".$first_array[0]['pymtMode']."','".$first_array[0]['bank_name']."')")){
				mysql_query("update tbl_reg_logs set form_no='manual_inv_created' where inv_no= '".$first_array[0]['inv_no']."' and memid = '".$first_array[0]['memid']."' ");
				updateTbltbl_updated_reg_logs($first_array[0]['memid']);
				}
			}
		}
		
	}	 */
	if (strpos($currTime, '06:00') !== false)
	{
		/*
		*  delete tables starting with tmpTblMagazineExcelDnld_ from steel360 db..; tyhese tabels are created  at steeladmin/magazine_filter.php
		*
		*/
		delete_same_pattern_tables("
				SHOW TABLES 
				FROM steelmin_steel360 
				where Tables_in_steelmin_steel360 like '%tmpTblMagazineExcelDnld_%'
			", 'Tables_in_steelmin_steel360');
	
		/*
		*  Expire steel 360 records on every 21st of month
		*
		*/
		if( 21 == date('d') )
		{
			mysql_query(
			"
				update tbl_reg_logs
				set status = 'Expired'
				where enddate <= '" . date('Y-m-22') . "'
				AND f_product IN ( 'M', 'A' )
				AND status = 'Active'
			");
		}
		/*
		*  make flag = 1 for 3 records of tbl_gallery and make flag = 0 for rest of records
		*
		*/
	   $sql=mysql_fetch_array(mysql_query("select count(*) as cnt from tbl_gallery"));
	   if($sql['cnt']>3)
	   {
		   $res=mysql_query("select * from tbl_gallery where flag=1 order by id asc");
		   while($row=mysql_fetch_array($res))
		   {
			  $arr[]=$row['id'];
		   }
		   
		   if(!empty($arr))
		   {
			   $last_id=end($arr);
			   //echo "select * from tbl_gallery where flag=0 and id>'$last_id' order by id asc limit 0,3"; exit;
			   $rs=mysql_query("select * from tbl_gallery where flag=0 and id>'$last_id' order by id asc limit 0,3");
			   $num=mysql_num_rows($rs);
			   if($num>0)
			   {
				   if($num==3)
				   {
					  mysql_query("update tbl_gallery set flag=0 where flag=1");
					  while($rw=mysql_fetch_array($rs))
					  {
						  
						  mysql_query("update tbl_gallery set flag=1 where id='".$rw['id']."'");
					  }
				   }
				   else{ 
						  $rem=3-$num;
						  mysql_query("update tbl_gallery set flag=0 where flag=1");
						  while($rw=mysql_fetch_array($rs))
						  {
							 mysql_query("update tbl_gallery set flag=1 where id='".$rw['id']."'");
						  }
						  $rs_l=mysql_query("select * from tbl_gallery where flag=0 order by id asc limit 0,$rem");
						  while($rw_l=mysql_fetch_array($rs_l))
						  {
							 mysql_query("update tbl_gallery set flag=1 where id='".$rw_l['id']."'");
						  }
					   }
			   }
			   else{
				   
					  $first=$arr[0];
					  mysql_query("update tbl_gallery set flag=0 where flag=1");
					 // echo "UPDATE tbl_gallery SET flag=1 where id!=$first ORDER BY id ASC LIMIT 3"; exit;
					  mysql_query("UPDATE tbl_gallery SET flag=1 where id!=$first ORDER BY id ASC LIMIT 3");
					 
				   }
		   }
		   else
		   {
				mysql_query("UPDATE tbl_gallery SET flag=1 ORDER BY id ASC LIMIT 3");
				
		   }
	   }
	   else
	   {
	      mysql_query("UPDATE tbl_gallery SET flag=1 ");
	   }	
	}		


	
	/*if (strpos($currTime, '10:43') !== false || strpos($currTime, '12:11') !== false || strpos($currTime, '13:26') !== false || strpos($currTime, '16:07') !== false || strpos($currTime, '17:21') !== false || strpos($currTime, '15:48') !== false || strpos($currTime, '17:42') !== false || strpos($currTime, '18:26') !== false)
		updateTbltbl_updated_reg_logs();*/
		
	//update  table tbl_updated_reg_logs
	function updateTbltbl_updated_reg_logs1()
	{
		
		mysql_query("
			create table tmp3
			SELECT memid, status, f_product, f_tenure, selected_products, tenders_group, startdate, enddate 
			from tbl_reg_logs 
			where inv_no in
			(
				   select distinct inv_no from tbl_invoice_log where  inv_type ='T'  and cancel_invoice = 'N' and inv_no not like 'PROFO%'
				   union
				   select distinct inv_no from tbl_inv_hist  where inv_no not like 'PROFO%'
			)
			UNION
			SELECT memid, status, f_product, f_tenure, selected_products, tenders_group , startdate, enddate
			FROM `tbl_reg_logs`
			WHERE receipt_no='Complementary'
			UNION
			SELECT memid, status, f_product, f_tenure, selected_products, tenders_group , startdate, enddate
			FROM `tbl_reg_logs`
			WHERE f_product in ('S', 'W', 'T')
			AND f_tenure like '%year%'
			AND inv_no = ''
			AND startdate <> '0000-00-00'
			AND enddate <> '0000-00-00'
			AND ((comments = 'status changed from Free Trial to One year' 
			AND status = 'Active') OR status = 'Active')			
		");

		mysql_query("
			create table tmp2
			select memid, f_product
			from tbl_reg_logs
			where status = 'Active'
			and f_tenure = 'Free Trial'		
		");
		
		$q = "
			select res1.*
			from tmp3 as res1
			LEFT OUTER JOIN	tmp2 as res2
				
			ON res1.memid = res2.memid
			AND res1.f_product = res2.f_product
			WHERE  res2.memid IS NULL		
		";
		
		/* $q   = "
					SELECT memid, status, f_product, f_tenure, selected_products, tenders_group, startdate, enddate 
					from tbl_reg_logs 
					where inv_no in
					(
						   select distinct inv_no from tbl_invoice_log where  inv_type ='T'  and cancel_invoice = 'N' and inv_no not like 'PROFO%'
						   union
						   select distinct inv_no from tbl_inv_hist  where inv_no not like 'PROFO%'
					)
					UNION
					SELECT memid, status, f_product, f_tenure, selected_products, tenders_group , startdate, enddate
					FROM `tbl_reg_logs`
					WHERE receipt_no='Complementary'
					UNION
					SELECT memid, status, f_product, f_tenure, selected_products, tenders_group , startdate, enddate
					FROM `tbl_reg_logs`
					WHERE f_product in ('S', 'W', 'T')
					AND f_tenure like '%year%'
					AND inv_no = ''
					AND startdate <> '0000-00-00'
					AND enddate <> '0000-00-00'
					AND ((comments = 'status changed from Free Trial to One year' 
					AND status = 'Active') OR status = 'Active')
			   ";*/
/*					UNION
					SELECT memid, status, f_product, f_tenure, selected_products, tenders_group 
					FROM `tbl_reg_logs`
					WHERE `selected_products` LIKE  '%NEWS%'
					AND f_tenure like '%year%'
					AND f_product = 'S'
					UNION
					SELECT memid, status, f_product, f_tenure, selected_products, tenders_group 
					FROM `tbl_reg_logs` 
					WHERE `pymtMode` = 'NEFT/Online' 
					and amtPaid in (0, '') 
					and status <> 'pending' 
					and f_product in ('W', 'S') 
					and `paymentstatus` = 'Paid' 					
*/			   
		$rs = mysql_query($q) or die(mysql_error());
		
		$res_arr = array();
		$namesW=array();$namesS=array();$namesT=array();
		while($rowSet = mysql_fetch_array($rs,MYSQL_ASSOC))
		{
			//tbl_updated_reg_logs
			if( "W" == $rowSet['f_product'] )
				$namesW[] = $rowSet['memid'];
			elseif( "S" == $rowSet['f_product'] )
				$namesS[] = $rowSet['memid'];
			elseif( "T" == $rowSet['f_product'] )
				$namesT[] = $rowSet['memid'];
				
			$sel_prod = $rowSet['selected_products'];
			if($rowSet['f_product']=='T'){
				$sel_prod = $rowSet['tenders_group'];
			}
			if($rowSet['status']=='Active'){
				if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['active_products']))
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['active_products'].=",";
					
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['active_products'] .= $sel_prod;
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['startdate'] = $rowSet['startdate'];
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['enddate'] = $rowSet['enddate'];
			}else{
				if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['nonactive_products']))
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['nonactive_products'].=",";
				
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['nonactive_products'].= $sel_prod;
				
				if( !isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['startdate']) )
				{
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['startdate'] = $rowSet['startdate'];
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['enddate'] = $rowSet['enddate'];
				}
			}
		}
		
		///// not paid
		/*$result = mysql_query("
								select distinct memid from tbl_invoice_log where (inv_no like 'Web/%' or inv_no like 'All/%') and inv_type ='T'  and cancel_invoice = 'N'
								union 
								select distinct memid from tbl_inv_hist where inv_no like 'Web/%' or inv_no like 'All/%'
							");
		$namesW=array();
		$namesW[]=0;
		while ($row = mysql_fetch_row($result))
		 $namesW[]=$row[0];
		mysql_free_result($result);
		
		$result = mysql_query("select distinct memid from tbl_invoice_log where (inv_no like 'sms/%' or inv_no like 'All/%') and inv_type ='T'  and cancel_invoice = 'N'
								union 
								select distinct memid from tbl_inv_hist where inv_no like 'sms/%' or inv_no like 'All/%'");
		//echo "<br /> qry count:" . mysql_num_rows($result) . "<br />"; 						
		$namesS=array();
		 $namesS[]=0;
		while ($row = mysql_fetch_row($result))
		 $namesS[]=$row[0];
		//echo "<br /> arr count:" .count($namesS) . "<br />"; 						
		mysql_free_result($result);
		
		$result = mysql_query("select distinct memid from tbl_invoice_log where (inv_no like 'tender/%') and inv_type ='T'  and cancel_invoice = 'N'
								union 
								select distinct memid from tbl_inv_hist where inv_no like 'tender/%'");
		$namesT=array();
		 $namesT[]=0;
		while ($row = mysql_fetch_row($result))
		 $namesT[]=$row[0];
		
		mysql_free_result($result);*/
		
		$names['W'] = implode(",",$namesW);
		$names['S'] = implode(",",$namesS);
		$names['T'] = implode(",",$namesT);
		
		foreach($names as $f_type=>$ids){
			if( "" != $ids )
			{
				$q   = "
					SELECT memid, status, 	f_product, 	f_tenure, 	selected_products, 	tenders_group, startdate, enddate 
					from tbl_reg_logs
					where memid not in 
					 (
						$ids
					 )
					 and f_product = '$f_type' 
				";  
	/* union 
					select memid, status, 	f_product, 	f_tenure, 	selected_products, 	tenders_group, startdate, enddate 
					from tbl_reg_logs 
					where comments = 'status changed from Free Trial to One year'
					and f_product = '$f_type' 			*/
				$rs = mysql_query($q) or die($q);
			
				//$res_arr = array();
				while($rowSet = mysql_fetch_array($rs,MYSQL_ASSOC))
				{
					$sel_prod = $rowSet['selected_products'];
					if($rowSet['f_product']=='T'){
						$sel_prod = $rowSet['tenders_group'];
					}
					if($rowSet['status']=='Active'){
						if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['active_products']))
							$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['active_products'].=",";
							
						$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['active_products'] .= $sel_prod;
						$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['startdate'] = $rowSet['startdate'];
						$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['enddate'] = $rowSet['enddate'];
					}else{
						if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['nonactive_products']))
							$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['nonactive_products'].=",";
						
						$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['nonactive_products'].= $sel_prod;
						if( !isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['startdate']) )
						{
							$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['startdate'] = $rowSet['startdate'];
							$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['enddate'] = $rowSet['enddate'];
						}
					}
				}
			}
		}
		//echo "<br /> 24792 details:" . $res_arr[24792]['S'] . "<br />"; die;
		
		/////complementary
		/*$q   = "SELECT *
				FROM `tbl_reg_logs`
				WHERE receipt_no='Complementary'
				";
		$rs = mysql_query($q) or die(mysql_error());
		
		//$res_arr = array();
		while($rowSet = mysql_fetch_array($rs,MYSQL_ASSOC))
		{
			$sel_prod = $rowSet['selected_products'];
			if($rowSet['f_product']=='T'){
				$sel_prod = $rowSet['tenders_group'];
			}
			if($rowSet['status']=='Active'){
				if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['active_products']))
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['active_products'].=",";
					
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['active_products'] .= $sel_prod;
			}else{
				if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['nonactive_products']))
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['nonactive_products'].=",";
				
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['nonactive_products'].= $sel_prod;
			}
		}*/
		//print_r($res_arr);
		mysql_query("truncate table tbl_updated_reg_logs	 ");
		$currDateTime = $GLOBALS['currDateTime'];
		foreach($res_arr as $memid=>$serv_arr):
			foreach($serv_arr as $services=>$_arr):
				foreach($_arr as $paid_unpaid=>$arr)://paid_unpaid
					$active_products = isset($arr['active_products'])?$arr['active_products']:'';
					$nonactive_products = isset($arr['nonactive_products'])?$arr['nonactive_products']:'';
					
					if($active_products)$status = 'Active';else $status = 'Inactive';
					
					$nonactive_products = (implode(',', array_keys(array_flip(explode(',', preg_replace('/,+/', ',',$nonactive_products))))));
					$active_products = (implode(',', array_keys(array_flip(explode(',', preg_replace('/,+/', ',',$active_products))))));
					$startdate = $arr['startdate'];
					$enddate = $arr['enddate'];
					mysql_query("INSERT INTO tbl_updated_reg_logs (created_on, memid, services, paid_unpaid, status, active_products, nonactive_products,startdate,enddate) values ('$currDateTime', '$memid', '$services', '$paid_unpaid', '$status', '$active_products', '$nonactive_products','$startdate','$enddate')");
					
				endforeach;
			endforeach;
		endforeach;
		
		//mysql_query("delete from  tbl_updated_reg_logs	where services='M'  ");	
		mysql_query("drop table tmp2 ");	
		mysql_query("drop table tmp3 ");	
	}
	/* function updateTbltbl_updated_reg_logs()
	{
		$q   = "SELECT memid, status, 	f_product, 	f_tenure, 	selected_products, 	tenders_group from tbl_reg_logs where 
		f_tenure LIKE '%Year%'
		AND status <> 'pending'
		AND comments <> 'status changed from Free Trial to One year'
		AND ( 
				inv_no IN
				(
					SELECT inv_no
					FROM tbl_invoice_log
					where cancel_invoice = 'N'
					union 
					select inv_no
					from tbl_inv_hist			
				)
				
				OR
				(
					inv_no = ''
					AND (
						comments = 'Succesful transaction'
						OR paymentstatus = 'PAID'
						OR `pymtMode` <> ''
					) 
					AND `pymtMode` not LIKE '%com%tary%'
					AND `pymDtls` not LIKE '%com%tary%'
					AND `pymtMode` not in ('', 'Free Trial')
					AND `pymDtls` not like '%Will Pay%' 
					AND pymDtls not like '%provider%'
					AND amtPaid <> '0'
					AND amtPaid <> '1/-'
				)
			)";
		$rs = mysql_query($q) or die(mysql_error());
		
		$res_arr = array();
		while($rowSet = mysql_fetch_array($rs,MYSQL_ASSOC))
		{
			//tbl_updated_reg_logs
			$sel_prod = $rowSet['selected_products'];
			if($rowSet['f_product']=='T'){
				$sel_prod = $rowSet['tenders_group'];
			}
			if($rowSet['status']=='Active'){
				if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['active_products']))
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['active_products'].=",";
					
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['active_products'] .= $sel_prod;
			}else{
				if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['nonactive_products']))
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['nonactive_products'].=",";
				
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['paid']['nonactive_products'].= $sel_prod;
			}
		}
		
		///// not paid
		$result = mysql_query("
								select distinct memid from tbl_invoice_log where (inv_no like 'Web/%' or inv_no like 'All/%') and inv_type ='T' and cancel_invoice = 'N'
								union 
								select distinct memid from tbl_inv_hist where inv_no like 'Web/%' or inv_no like 'All/%'
							");
		$namesW=array();
		$namesW[]=0;
		while ($row = mysql_fetch_row($result))
		 $namesW[]=$row[0];
		mysql_free_result($result);
		
		$result = mysql_query("select distinct memid from tbl_invoice_log where (inv_no like 'sms/%' or inv_no like 'All/%') and inv_type ='T' and cancel_invoice = 'N'
								union 
								select distinct memid from tbl_inv_hist where inv_no like 'sms/%' or inv_no like 'All/%'");
		$namesS=array();
		 $namesS[]=0;
		while ($row = mysql_fetch_row($result))
		 $namesS[]=$row[0];
		
		mysql_free_result($result);
		
		$result = mysql_query("select distinct memid from tbl_invoice_log where (inv_no like 'tender/%') and inv_type ='T' and cancel_invoice = 'N'
								union 
								select distinct memid from tbl_inv_hist where inv_no like 'tender/%'");
		$namesT=array();
		 $namesT[]=0;
		while ($row = mysql_fetch_row($result))
		 $namesT[]=$row[0];
		
		mysql_free_result($result);
		
		$names['W'] = implode(",",$namesW);
		$names['S'] = implode(",",$namesS);
		$names['T'] = implode(",",$namesT);
		
		foreach($names as $f_type=>$ids){
			$q   = "SELECT memid, status, 	f_product, 	f_tenure, 	selected_products, 	tenders_group 
			from tbl_reg_logs
			where memid not in 
			 (
				$ids
			 )
			 and f_product = '$f_type' 
			union 
			select memid, status, 	f_product, 	f_tenure, 	selected_products, 	tenders_group 
			from tbl_reg_logs 
			where comments = 'status changed from Free Trial to One year'
			and f_product = '$f_type' 
			";  
			$rs = mysql_query($q) or die(mysql_error());
		
			//$res_arr = array();
			while($rowSet = mysql_fetch_array($rs,MYSQL_ASSOC))
			{
				$sel_prod = $rowSet['selected_products'];
				if($rowSet['f_product']=='T'){
					$sel_prod = $rowSet['tenders_group'];
				}
				if($rowSet['status']=='Active'){
					if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['active_products']))
						$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['active_products'].=",";
						
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['active_products'] .= $sel_prod;
				}else{
					if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['nonactive_products']))
						$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['nonactive_products'].=",";
					
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['not-paid']['nonactive_products'].= $sel_prod;
				}
			}
		}
		
		
		/////complementary
		$q   = "SELECT *
		FROM `tbl_reg_logs`
		WHERE inv_no = ''
		AND f_tenure LIKE '%Year%'
		AND comments <> 'status changed from Free Trial to One year'
		AND STATUS <> 'pending'
		AND f_product IN (
			'W', 'S'
		)
		AND (
			`pymtMode` LIKE '%ntary'
			OR `pymDtls`  like '%Will Pay%' 
			OR pymDtls like '%provider%'
			OR `pymtMode` in ('Free Trial')
			OR (amtPaid = '0' AND  paymentstatus <> 'Trxn Failed' AND comments <> 'Transaction has failed.')
			OR amtPaid = '1/-'
		)";
		$rs = mysql_query($q) or die(mysql_error());
		
		//$res_arr = array();
		while($rowSet = mysql_fetch_array($rs,MYSQL_ASSOC))
		{
			$sel_prod = $rowSet['selected_products'];
			if($rowSet['f_product']=='T'){
				$sel_prod = $rowSet['tenders_group'];
			}
			if($rowSet['status']=='Active'){
				if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['active_products']))
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['active_products'].=",";
					
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['active_products'] .= $sel_prod;
			}else{
				if(isset($res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['nonactive_products']))
					$res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['nonactive_products'].=",";
				
				$res_arr[$rowSet['memid']][$rowSet['f_product']]['complementary']['nonactive_products'].= $sel_prod;
			}
		}
		//print_r($res_arr);
		mysql_query("truncate table tbl_updated_reg_logs	 ");
		$currDateTime = $GLOBALS['currDateTime'];
		foreach($res_arr as $memid=>$serv_arr):
			foreach($serv_arr as $services=>$_arr):
				foreach($_arr as $paid_unpaid=>$arr)://paid_unpaid
					$active_products = isset($arr['active_products'])?$arr['active_products']:'';
					$nonactive_products = isset($arr['nonactive_products'])?$arr['nonactive_products']:'';
					
					if($active_products)$status = 'Active';else $status = 'Inactive';
					
					$nonactive_products = (implode(',', array_keys(array_flip(explode(',', preg_replace('/,+/', ',',$nonactive_products))))));
					$active_products = (implode(',', array_keys(array_flip(explode(',', preg_replace('/,+/', ',',$active_products))))));
					
					mysql_query("INSERT INTO tbl_updated_reg_logs (created_on, memid, services, paid_unpaid, status, active_products, nonactive_products) values ('$currDateTime', '$memid', '$services', '$paid_unpaid', '$status', '$active_products', '$nonactive_products')");
					
				endforeach;
			endforeach;
		endforeach;
		
		mysql_query("delete from  tbl_updated_reg_logs	where services='M'  ");	
	} */
	
	function wp_get_all_tags( $args = '' ) {
		$idTags = array();
		$tags = get_terms('post_tag');
		foreach ( $tags as $key => $tag ) {
			if ( 'edit' == 'view' )
			$link = get_edit_tag_link( $tag->term_id, 'post_tag' );
			else
			$link = get_term_link( intval($tag->term_id), 'post_tag' );
			if ( is_wp_error( $link ) )
			return false;

			$idTags[$key] = $tag->name;
		}
		return $idTags;
	}

	// update tags in the file
	if ( strpos($currTime, '14:30:') !== false || strpos($currTime, '22:00:') !== false )
	{
		require('news/wp-blog-header.php');

		$tagsArr = wp_get_all_tags();
		$message = json_encode($tagsArr);	
		$myFile ='jQuery-Autocomplete/content/tags_json.txt';
	
		if (file_exists($myFile)) {
		   unlink($myFile);
		  //$fh = fopen($myFile, 'a');
		  $fh = fopen($myFile, 'w');
		  fwrite($fh, $message."\n");
		} else {
		  $fh = fopen($myFile, 'w');
		  fwrite($fh, $message."\n");
		}
		fclose($fh); 
	}


	
/* 	if( ( "Thu" == $dayOfWeek || "Mon" == $dayOfWeek ) && strpos($currTime, '10:') !== false )
		require_once (dirname( __FILE__ ) . "/mt.php"); */
		


 	if (strpos($currTime, '10:05') !== false){
		sendSignsSMSToNewUser();
	}	

 /* 	if (strpos($currTime, '09:20') !== false && "Sun" != $dayOfWeek)
	{
		activateIdsCreatedfromExcel();
		$sender_name = 'SteelMint';
		$sender_email = 'info@steelmint.com';
		$headers = 'From:' . $sender_name . '<' . $sender_email . '>' . "\r\n" .
			'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
			'Reply-To: ' . $sender_email . "\r\n" .
			'X-Mailer: PHP/' . phpversion();
		mail("tarun@steelmint.com", "5 ids activated from excel files ", "", $headers,"www.steelmint.com -f$sender_email");
	}  */

	if (strpos($currTime, '09:00') !== false)
	{
		//include "inc/desconfig.php";
		//include_once "steel360/config1.php";
		
		$currDate = $GLOBALS['currDate'];
		$currDayOfMonth = date("d", strtotime($currDate));
		$n_mnt = date("M-Y", strtotime($currDate .' +1 months'));
		$c_mnt = date("M-Y", strtotime($currDate));
		$p_mnt = date("M-Y", strtotime($currDate .' -1 months'));
		
		$flag = 0;
		switch ($currDayOfMonth)
		{
			case 21:
				nMntMailer($currDate, $n_mnt);
				cMntMailer($currDate, $c_mnt);
				$flag = 1;
			break;
			
			/*case 20:
				cMntMailer($currDate, $c_mnt);
				$flag = 1;
			break;*/
			
			case 25:
				nMntMailer($currDate, $n_mnt);
				$flag = 1;
			break;
			
			case 5:
			case 10:
				pMntMailer($currDate, $p_mnt);
				$flag = 1;
			break;
		}
		
/* 		if( $flag == 1 )
		{
			$sender_name = 'SteelMint';
			$sender_email = 'info@steelmint.com';
			$headers = 'From:' . $sender_name . '<' . $sender_email . '>' . "\r\n" .
				'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
				'Reply-To: ' . $sender_email . "\r\n" .
				'X-Mailer: PHP/' . phpversion();
			mail("tarun@steelmint.com", "SteelMint: 360 remionders sent", "", $headers,"www.steelmint.com -f$sender_email");
		} */
		//include "inc/desconfig.php";
	}
	
/*	if (strpos($currTime, '23:45') !== false)
	{
		//include "inc/desconfig.php";
		//include_once "steel360/config1.php";
		$res = mysql_query(
		"
			SELECT memid, id, startdate, f_tenure
			FROM `tbl_reg_logs`
			WHERE f_product = 'M'
			and status = 'Active'
		"
		);
		
		$cnt = '';
		while($row = mysql_fetch_array($res))
		{
			$id = $row['id'];
			$startdate = $row['startdate'];
			if( 38055 == $row['memid'] )
				$startdate = '2013-06-01';
			if( 6891 == $row['memid'] )
				$startdate = '2013-08-01';
			if( 37247 == $row['memid'] )
				$startdate = '2013-07-01';
			if( 5232 == $row['memid'] )
				$startdate = '2013-07-01';
			$ftenure = $row['f_tenure'];
			$day_start_date = explode("-", $startdate);
			if( $day_start_date[2] == '31' )
				$startdate = $day_start_date[0] . "-" . $day_start_date[1] . '-30';
			if( $day_start_date[2] > 15 )
			{
				//increment month in the startdate
				$strt_date = date('Y/m/d', strtotime($startdate . '+1 month'));
				if( "One Year" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+11 months'));
				if( "Two Years" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+23 months'));
				if( "Free Trial-Two Months" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+1 months'));
				if( "Free Trial-One Month" == $ftenure || "Free Trial" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+0 months'));
				if( "Free Trial-Three Months" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+2 months'));
			}
			else
			{
				//consider current  month
				$strt_date = date('Y/m/d', strtotime($startdate));
				if( "One Year" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+11 months'));
				if( "Two Years" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+23 months'));
				if( "Free Trial-Two Months" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+1 months'));
				if( "Free Trial-One Month" == $ftenure || "Free Trial" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+0 months'));
				if( "Free Trial-Three Months" == $ftenure )
					$end_date = date('Y/m/d', strtotime($strt_date . '+2 months'));
			}
			$ex = explode("/", $strt_date);
			$startYear = $ex[0];
			$startMonth = $ex[1];
			if( 25509 == $row['memid'] )
				$end_date = date('Y/m/d', strtotime($end_date . '-2 months'));
			if( 33935 == $row['memid'] || 31223 == $row['memid'] )
				$end_date = date('Y/m/d', strtotime($end_date . '-3 months'));
			if( 37247 == $row['memid'] )
				$end_date = date('Y/m/d', strtotime($end_date . '-1 months'));
			if( 35986 == $row['memid'] )
				$end_date = date('Y/m/d', strtotime($end_date . '-1 months'));
			if( 34632 == $row['memid'] )
				$end_date = date('Y/m/d', strtotime($end_date . '-1 months'));
			if( 9260 == $row['memid'] )
				$end_date = date('Y/m/d', strtotime($end_date . '-1 months'));
			if( 3317 == $row['memid'] )
				$end_date = date('Y/m/d', strtotime($end_date . '-2 months'));
			if( 2980 == $row['memid'] )
				$end_date = date('Y/m/d', strtotime($end_date . '+1 months'));
			$ex = explode("/", $end_date);
			$endYear = $ex[0];
			$endMonth = $ex[1];
			$startDate = strtotime("$startYear/$startMonth/01");
			$endDate   = strtotime("$endYear/$endMonth/01");
			$currentDate = $endDate;
			$strDates = ''; $endMonthYear = '';
			while ($currentDate >= $startDate) {
				if( '' == $strDates )
				{
					$strDates = date('M-Y',$currentDate);
					$endMonthYear = $strDates;
				}
				else
					$strDates .= "," . date('M-Y',$currentDate);
				$currentDate = strtotime( date('Y/m/01/',$currentDate).' -1 month');
			}
			
			$currMonthYear = date('M-Y', strtotime($GLOBALS['currDate']));
			$currDayOfDate = date('d', strtotime($GLOBALS['currDate']));
			
			$expry = "";
			if( ($endMonthYear == $currMonthYear && $currDayOfDate == 15) || (strtotime($currMonthYear) > strtotime($endMonthYear)) )
				$expry = " ,status='Expired' ";
			
			$res1 = mysql_query(
			"
				update `tbl_reg_logs`
				set issues_to_go = '$strDates' $expry
				WHERE id = '$id'
			"
			);
		}
	}*/
//	if (strpos($currTime, '09:15') !== false && $dayOfWeek != 0 and $dayOfWeek != 6)
//	{
//		activate_pankaj_karnataka_template_ids();
//		activate_hupen_template_ids();
//	}
	if (strpos($currTime, '20:10:') !== false)
	{
		include "https://www.steelmint.com/gmail-imap/readattachement.php";
	}
/*
	if( $currTime == '11:00:01' )
	{
		include "inc/config1.php";
		$c_date  = date('Y-m-d',strtotime($currDate.'+15 days'));
		$result = mysql_query("SELECT id FROM tbl_members WHERE expiry like '$c_date%' Order by id")
					or die(mysql_error());
		$members_id = '';
		 while($row = mysql_fetch_array( $result )) {
			if($members_id=='')
				$members_id = $row[0];
			else
				$members_id.=','.$row[0];
		 }
		$headers = "From:SteelMint<info@steelmint.com>" . "\r\n" .
		'MIME-Version: 1.0' . "\r\n" .
		'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
		"Reply-To: info@steelmint.com " . "\r\n" .
		"X-Mailer: PHP/" . phpversion();
		mail("hupendra@steelmint.com", "Member Ids expiring on: " .  $c_date, $members_id, $headers,"SteelMint -finfo@steelmint.com");
	}
*/
/*
	if (strpos($currTime, '11:00:') !== false)
	{
		$dateSixMonthBefore  = date('Y-m-d',strtotime("-6 months"));
                 $qry1 ="select distinct id as memid
				from tbl_members where id NOT IN
				(
					select distinct memid
					from tbl_reg_logs
					where f_product IN ('W', 'S')
					and (status = 'Active' OR enddate > '$dateSixMonthBefore')
				)
				and mood NOT IN ('3', '5')
				and free_trial_active = '0'
                ORDER BY `id` ASC
				limit 0,10";
		$result = mysql_query($qry1);
		$sql= "SELECT `f_product` FROM `tbl_product_items` WHERE `web_sms`='W'";
		$result2 = mysql_query($sql);
		$mtArr= array();
		while($rs2 = mysql_fetch_array($result2))
		{
			$mtArr[] = $rs2['f_product'];
		}
		$str='';
		foreach($mtArr as $pro){
			if($str!='')
				$str.=",$pro";
			else
				$str.="$pro";
		}
		$disp_table = '';
		$disp_table .= '<span><strong>Details of the ids activated are as follows:</strong></span><table cellpadding="6" rules="all" style="border:2px solid #76C0C7; "><tr><td><strong>Mem-id</strong></td><td><strong>Product Type</strong></td><td><strong>email</strong></td><td><strong>Phone No.</strong></td><td><strong>Company Name</strong></td>';
		while ($rs = mysql_fetch_array($result))
		{
			$memid = $rs['memid'];
			$query = "select * from tbl_members where id='$memid'";
			$result1 = mysql_query($query);
			$row = mysql_fetch_array($result1);
			$username = $row['username'] ;
			if($row['password'] == '')
			{
				$password = generatePassword();
				$update_sql = "UPDATE tbl_members SET password = '$password',mood = '9',free_trial_active = '1' where id='$memid' ";
				mysql_query($update_sql);
			}
			else
				$password = $row['password'] ;
			$xyz = $row['name'] ;
			$timezone = new DateTimeZone( "Asia/Calcutta" );
			$currDate=$date->format( 'Y-m-d' );
			$currDateTime=$date->format( 'Y-m-d H:i:s' );
			$enddate  = date('Y-m-d', strtotime($currDate . '+10 days'));
			//echo "pro is" .$str;
			 $tabres ='Dear '.$xyz.'<br />
			<br />
			 SteelMint wishes you a very Happy New Year - 2013.<br />
			<br />
			We are happy to inform you that based on your earlier registration, we are offering you 10 DAYS FREE TRIAL service on your previous account with more newly added steel product prices and News coverage.<br />
			<br />
			<strong>Your Login credentials are:</strong><br />
			<br />
			<strong>Username</strong>: '.$username.'<br />
			<br />
			<strong>Password</strong>: '.$password.'<br />
			<br />
			Link: <a href="www.steelmint.com/logincustomer" target ="_blank">www.steelmint.com/logincustomer</a>
			<br />
			<br />
			We are sure that our better than ever before services and product coverage will definitely help you take some crucial decisions in your daily trade.<br />
			<br />
			Look forward to your valuable feedback to improve our services, all the time.<br />
			<br />
			For any assistance related to membership, please call us on +91 9575100530. You can also reply to this email.<br />
			<br />
			Thanks and regards<br />
			Team SteelMint';
			$ins = "insert into tbl_reg_logs (f_time,memid,startdate,enddate,status,f_product, f_tenure,selected_products,prev_freeTrial, created_on) values ('" . $currTime . "','" . $memid . "','" . $currDate . "','" .$enddate . "','Active','W','Free Trial','" . $str . "','" . $str . "', '$currDateTime')";
			mysql_query($ins);
			$ins1 = "insert into tbl_reg_logs (f_time,memid,startdate,enddate,status,f_product, f_tenure,selected_products,prev_freeTrial, created_on) values ('" . $currTime . "','" . $memid . "','" . $currDate . "','" .$enddate . "','Active','S','Free Trial','NEWS','NEWS', '$currDateTime')";
			mysql_query($ins1);
			$to      = $row['email'];
			$subject = 'Steel Prices and News to Benefit in Your Daily Trade';
			$headers = 'From: SteelMint<info@steelmint.com>' . "\r\n" .
				'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
				'Bcc: [email]nishu@steelmint.com[/email]' . "\r\n" .
				'X-Mailer: PHP/' . phpversion();
			mail($to, $subject, $tabres, $headers);
			$disp_table .= '<tr>';
			$disp_table .= '<td>' . $row['id'] . '</td><td>' . getProdListFrmIdNew( "tbl_producttype",$row['protype']) . '</td><td>' . $row['email'] . '</td><td>' . $row['phoneno'] . '</td><td>' . $row['company'] . '</td>';
			$disp_table .= '</tr>';
		}
		$disp_table .= '</table>';
		$subject = '10 ids have been activated';
		$headers = 'From: SteelMint<info@steelmint.com>' . "\r\n" .
			'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
			'Bcc: [email]nishu@steelmint.com[/email]' . "\r\n" .
			'X-Mailer: PHP/' . phpversion();
		mail('sumit@steelmint.com,kapil@steelmint.com,rohan@steelmint.com,hupendra@steelmint.com,manish@steelmint.com', $subject, $disp_table, $headers);
	}
*/
	/*if (strpos($currTime, '08:00:') !== false)
	{
		//include "inc/config1.php";
		$currDate = $GLOBALS['currDate'];
		$lastWeek = date("Y-m-d",strtotime($currDate . '-7 days'));
		$result = mysql_query("select * from tbl_image_reports ");
		$i = '';
		if($cnt = mysql_num_rows($result)>0)
		{
			while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
			{
				$image = $row['list_of_imgs'];
				$report = $row['report_name'];
				$shw_img = $row['show_img'];
				$start_date = $row['start_date'];
				$diff = abs((strtotime($currDate) - strtotime($start_date))/86400);
				if ($diff > 7)
				{
					$arryimg = explode(',', $image);
					for($i = 0; $i < $cnt; $i++)
					{
						$arryimg = array_remove_value($arryimg, $shw_img);
						$rand_keys = array_rand($arryimg, 1);
						$result_img = $arryimg[$rand_keys];
						mysql_query("update tbl_image_reports set show_img = '$result_img', start_date = '$currDate' where report_name = '$report'");
					}
				}
			}
		}
	}*/
	/*if (strpos($currTime, '10:01:') !== false)
	{
		int_freetrail();
	}*/
	/*if (strpos($currTime, '23:59:') !== false)
	{
		shuffleTbl_shuffle();
	}*/
	
	if (strpos($currTime, '22:59:') !== false)
	{
		$currDate = $date->format( 'Y-m-d' );
		$sql_mem_reg_logs = "select id from tbl_reg_logs
							 where acc_ver_pending = '1' and DATE_ADD(startdate, INTERVAL 7 DAY) <= '$currDate'
							 and f_product IN ('W','S')
							 and inv_no = ''
							 ";
		$res_members = mysql_query($sql_mem_reg_logs) or die(mysql_error());
		while($row_members = mysql_fetch_array($res_members,MYSQL_ASSOC))
		{
			$rs_update = mysql_query("update tbl_reg_logs set status = 'Accounts Verification Pending' where id=" . $row_members['id']);
			updateTbltbl_updated_reg_logs($row_members['id']);
		}
	}
/*
	if (strpos($currTime, '13:00:') !== false || strpos($currTime, '17:00:') !== false || strpos($currTime, '21:00:') !== false || strpos($currTime, '01:00:') !== false || strpos($currTime, '05:00:') !== false || strpos($currTime, '09:00:') !== false)
	{
		shuffleTbl_item_rotation();
	}
*/	
	/*if( strpos($currTime, '10:20:') !== false )
	{
		include "cronsms_new.php";
	}*/
	
/*	function getData($str, $link, $crncy)
	{
		$html = file_get_html($link);
		foreach($html->find("a[rel=$str]") as $e)
		{
			$res = mysql_query("insert into tbl_currency_watch(f_date, f_time, currency, f_price) values('" . $GLOBALS['currDate'] . "', '" . $GLOBALS['currTime'] . "', '$crncy', '" . number_format($e->innertext, 2) . "' )");
		}
	}
	if( strpos($currTime, '12:04:') !== false )
	{
		include('simple_html_dom.php');
		//include "inc/config1.php";
		getData("INR,USD,1,4", "https://www.xe.com", "INR") . "<br />"; //INR
		getData("EUR,USD,1,2", "https://www.xe.com", "EUR") . "<br />"; //EUR
		getData("JPY,USD,1,9", "https://www.xe.com", "JPY") . "<br />"; //JPY
		getData("GBP,USD,3,1", "https://www.xe.com", "GBP") . "<br />"; //GBP
		getData("TRY,USD,4,1", "https://www.xe.com/?r=4&c=TRY", "TRY") . "<br />"; //TRY
		getData("CNY,USD,4,1", "https://www.xe.com/?r=4&c=CNY", "CNY") . "<br />"; //CNY
	}
*/	
	/*if( strpos($currTime, '12:00:') !== false )
	{
		$action = "INSERT";
		include "steelmkt.php";
	}
	if (strpos($currTime, '14:00:') !== false || strpos($currTime, '16:00:') !== false || strpos($currTime, '18:00:') !== false || strpos($currTime, '20:00:') !== false)
	{
		$action = "EDIT";
		include "steelmkt.php";
	}*/
/*
	  if( $currTime == '23:45:01' )
	  {
		$firstFileSmall = '';
		$firstFileLarge = '';
		$secondFileSmall = '';
		$secondFileLarge = '';
		getDirectoryList ("ncdex/", $firstFileSmall, $firstFileLarge, $secondFileSmall, $secondFileLarge);
		  copy("ncdex/" . $firstFileSmall, "html/ncdex_small.jpg");
	  }
*/
	/* if( strpos($currTime, '07:54:') !== false )
	{
		$currDate = $GLOBALS['currDate'];
		mysql_query("insert into tbl_try values('for crongeneral1')");
		$sql_reglog = "Update tbl_reg_logs set status = 'Expired' where enddate < '$currDate' and status = 'Active' and f_product IN ('W','S','M', 'T')";
        $res_query = mysql_query($sql_reglog ) or die(mysql_error());
		$res = mysql_query(" UPDATE tbl_members SET logstatus='' WHERE logstatus='Active' ");
        webExpiryNotificatn($currDate,'Exp Today');
		$exp_bef_2_days = date("Y-m-d",strtotime($currDate . '+2 days'));
		webExpiryNotificatn($exp_bef_2_days,'Exp Bef 2 Days');
		$exp_bef_seven_days = date("Y-m-d",strtotime($currDate . '+7 days'));
		webExpiryNotificatn($exp_bef_seven_days,'Exp Bef 7 days');
		$exp_bef_fifteen_days = date("Y-m-d",strtotime($currDate . '+15 days'));
		webExpiryNotificatn($exp_bef_fifteen_days,'Exp Bef a month');
	} */
	function webExpiryNotificatn($end_date,$exp)
	{
		$currDate = $GLOBALS['currDate'];
		define('DOCROOT',substr(str_replace(pathinfo(__FILE__,PATHINFO_BASENAME),'',__FILE__),0,-1));
		$sql = "select *, count(y.memid)as cnt 
				from tbl_reg_logs y
				JOIN
				(
					select selected_products,memid,enddate,status,f_tenure
					from tbl_reg_logs 
					where enddate = '$end_date' 
					and status='Active' 
					and f_product = 'W' 
					and selected_products <> '' 
					and startdate <> '$currDate' 
					ORDER BY `tbl_reg_logs`.`memid`
				)x
				ON  y.memid = x.memid 
				and y.selected_products=x.selected_products
				and y.enddate>=x.enddate 
				and y.status='Active'
				group by y.memid
				having cnt=1 ";
		if($exp == "Exp Bef a month")
			$sql = str_replace("selected_products <> ''", "selected_products <> '' and f_tenure <> 'Free Trial'", $sql);
		$query = mysql_query($sql) or die(mysql_error());
		while($res = mysql_fetch_array($query))
		{
			$sql_members = "select * from tbl_members where id = '" . $res['memid'] ."' ";
			$res_members = mysql_query($sql_members) or die(mysql_error());
			$row_members = mysql_fetch_array($res_members);
			$RM_email = "";
			$name = "";
			$city = $row_members['city'];
			$country = $row_members['country'];
			$qry_city = mysql_query("
									select name from tbl_city where id = '$city'
						") or die(mysql_error());
			$res_city = mysql_fetch_array($qry_city);
			if($row_members['billing_name'] != '')
			{
				$name = $row_members['billing_name'];
			}
			else
			{
				$name = $row_members['name'];
			}
			$company = $row_members['company'];
			$expiry = $res['enddate'];
			$expiry_date = date('d F Y', strtotime($expiry));
			$RelManager = $row_members['relMngr'];
			$email = $row_members['email'];
			$qry_RM = mysql_query("
									select RM_phoneno,RM_email,RM_name from tbl_rel_manager where rel_manager = '$RelManager'
						") or die(mysql_error());
			$res_RM = mysql_fetch_array($qry_RM);
			$RM_email = $res_RM['RM_email'];
			$RM_name = $res_RM['RM_name'];
			$RM_phoneno = $res_RM['RM_phoneno'];
			if($RelManager == "-NA-")
			{
				$RM_name = "";
				$RM_email = "info@steelmint.com";
				$RM_phoneno = "";
			}
			else
				$RM_name .= "<br />";
			$my_message = '';
			
			$sub = '';
			$attchFile = '';
			if($exp == "Exp Bef 2 Days")
			{
				if( $res['f_tenure'] == 'Free Trial' )
				{
					$sub = "SteelMint: Your web trial is active for 2 more days; Renew Now!";
					$my_message = "
					Dear " . $name . " <br /><br />
					<div>This is a quick reminder to tell you that your membership is expiring after 2 days. We hope you are already in the process to renew your account, for any kind of assistance feel free to call me.</div><div><br></div><div style='color:red;'>I admire if you renew your membership before expiry to keep getting our services without any interruption.&nbsp;</div><div><br></div><div><b>You can quickly subscribe online here:</b>&nbsp;</div><div><a href='https://www.steelmint.com/memberegi'>www.steelmint.com/memberegi</a></div><div><br></div><div>Please refer the attached SteelMint Product &amp; Subscription Detail Sheet for more details.</div><div><br></div><div>For further support feel free to speak to me on +91 " . $RM_phoneno . ".&nbsp;</div><div><br></div><div>Have a great day! &nbsp;&nbsp;</div></div><div><br></div>
					Best regards<br /><span style=\"color:#666666\">
					" . $RM_name . "
					SteelMint Info Services LLP, India<br>
					ISO 9001:2008 Certified<br /><br /></span>
					<span style=\"color:#333333\"><br>
					**********************************************************************************************************<br />
					This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.<br /><br />
					**********************************************************************************************************<br /><br />
					SteelMint Info Services LLP, India<br />
					";	
				}	
				else
				{
					$sub = "SteelMint: Your web service is active for 2 more days!";
					$my_message = '
						<div>Dear ' . $name . '</div><div><br />Greetings from SteelMint..!!</div><div><br></div><div>A quick reminder to tell you that your web service for ' . $res['selected_products'] . ' will expire on 26 August 2013.</div><div><br></div><div>To continue services with <a href="https://www.steelmint.com">www.steelmint.com</a>, please renew your subscription.</div><div><b>Renew Online</b>: <a href="https://www.steelmint.com/memberegi">www.steelmint.com/memberegi</a></div><div><br></div><div>For more details reply to this email or contact me on +91 ' . $RM_phoneno . '.</div><div>Have a great day! &nbsp;</div><div><br></div><br /><br />Best regards<br /><span style=\"color:#666666\">
						' . $RM_name . '
						SteelMint Info Services LLP, India<br>
						ISO 9001:2008 Certified<br /><br /></span>
						<span style=\"color:#333333\"><br>
						**********************************************************************************************************<br />
						This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.<br /><br />
						**********************************************************************************************************<br /><br />
						SteelMint Info Services LLP, India<br />
					';			
				}	
			}
			
			if($exp == "Exp Today")
			{
				if( $res['f_tenure'] == 'Free Trial' )
				{
					$sub = "SteelMint: Your service with SteelMint is ending today!";
					$my_message = "
					Dear " . $name . " <br /><br />
					<div>It's a quick reminder to tell you that your web service is expiring today and you won’t have access to our services until you renew your account.</div><div><br></div><div>Renew online now: <a href='www.steelmint.com/memberegi'>www.steelmint.com/memberegi</a></div><div><br></div><div>In case you need any kind of support, feel free to call me on +91 " . $RM_phoneno . ".&nbsp;</div><div><br></div><div>Have a great day!</div><div><br></div>
					<br /><br />
					Best regards<br /><span style=\"color:#666666\">
					" . $RM_name . "
					SteelMint Info Services LLP, India<br>
					ISO 9001:2008 Certified<br /><br /></span>
					<span style=\"color:#333333\"><br>
					**********************************************************************************************************<br />
					This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.<br /><br />
					**********************************************************************************************************<br /><br />
					SteelMint Info Services LLP, India<br />
					";
				}	
				else	
				{
					$sub = "Your service with SteelMint is ending today!";
					$my_message = '
					Dear ' . $name . ' <br /><br />
					<div>This is to inform you that your web service is expiring today and your access to our services will resume once you renew your account.</div><div><br></div><div>Renew online now: <a href="https://www.steelmint.com/memberegi">www.steelmint.com/memberegi</a></div><div><br></div><div>For any kind of support, feel free to call me on +91 ' . $RM_phoneno . '.&nbsp;</div><div><br></div><div>Have a great day! &nbsp;</div><div><br></div>
					<br /><br />
					Best regards<br /><span style=\"color:#666666\">
					' . $RM_name . '
					SteelMint Info Services LLP, India<br>
					ISO 9001:2008 Certified<br /><br /></span>
					<span style=\"color:#333333\"><br>
					**********************************************************************************************************<br />
					This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.<br /><br />
					**********************************************************************************************************<br /><br />
					SteelMint Info Services LLP, India<br />
					';
				}	
			}
			if($exp == "Exp Bef a month")
			{
				$sub = "SteelMint: Your membership is expiring soon!";
				$my_message = '
				<div>Dear ' . $name . '</div><div><br />Greetings from SteelMint..!!</div><div><br></div><div>Thank you for being a patronage client for last one year.&nbsp;</div><div><br></div><div>Informing you that your one year membership for ' . $res['selected_products'] . ', is expiring soon and your services remain active for <b>15 days</b> from today.&nbsp;</div><div><br></div><div><font color="#ff0000">You should renew your account before expiry date to avail continuous services.</font></div><div><br></div><div>We are continuously improving our coverage, quality of reports and introducing new analysis tools to give you the most usable, accurate and timely information.</div><div><br></div><div>Doing so, we have started many new reports, started covering some new products, added new tools like Import/Export Statistics, Live Market Tracker, Tenders, Plant &amp; Machinery for Sale, Improved Archive Data and much more.</div><div><br></div><div><b>Most Preferred Membership Plan:&nbsp;</b></div><div><br></div><div>To avail premium and exclusive services, we offer you should opt for <b>Complete Web Service (Premium)</b>. Along with access to prices, news and reports it will also cover the new sections - Statistics, Tender, Live Market Tracker &amp; Archive Data Graphs.&nbsp;</div><div><br></div><div>Find more about subscription charges in the SteelMint Product &amp; Subscription Detail Sheet attached.</div><div><br></div><div><b>Major clients who bank on us:&nbsp;</b></div><div><b><br></b></div><div><b>Arcelor Mittal Group, NMDC, Vedanta Group, Tata Steel, Citigroup, Sesa Goa, Essar Steel, Reliance ADAG, Aditya Birla Group, Essar Group, Rungta Mining Group, CRU Group</b> and many more.</div><div><br></div><div>For any support please feel free to contact on +91 ' . $RM_phoneno . '.</div><div><br></div><div>Look forward to your continuous patronage.</div><div><br></div><div>Have a great day! &nbsp;</div><div><br></div><br /><br />Best regards<br /><span style=\"color:#666666\">
					' . $RM_name . '
					SteelMint Info Services LLP, India<br>
					ISO 9001:2008 Certified<br /><br /></span>
					<span style=\"color:#333333\"><br>
					**********************************************************************************************************<br />
					This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.<br /><br />
					**********************************************************************************************************<br /><br />
					SteelMint Info Services LLP, India<br />
				';
				
				if($country != '113')
					$attchFile = "/multipleattachmentmailphp/SteelMint - Product and Subscription Details_Overseas.pdf";
				else
					$attchFile = "/multipleattachmentmailphp/SteelMint - Product and Subscription Details_August13.pdf";
			}
			if($exp == "Exp Bef 7 days")
			{
				if( $res['f_tenure'] == 'Free Trial' )
				{
					if($country == '113')
					{
						$sub = "SteelMint: Your Trial Account is expiring soon!";
						$my_message = "
						<div>Dear " . $name . "</div><div><br /><br></div><div><div>We are glad to serve you over free trial period, I hope that you are making good use of the price and news available on the website and benefitting from it.&nbsp;</div><div><br></div><div>Taking this opportunity I would like to tell you about our best selling membership plan.&nbsp;</div><div><br></div><div><b>Complete Website Premium Membership</b>:&nbsp;</div><div><br></div><div>We offer you should opt for <b>Complete Web Service (Premium)</b>. Along with access to prices, news and reports it will also cover the new sections - Statistics, Tender, Live Market Tracker &amp; Archive Data Graphs.&nbsp;</div><div><br></div><div>Find more about subscription charges in the SteelMint Product &amp; Subscription Detail Sheet attached.</div><div><br></div><div>Let me know so that I can start your membership immediately after the expiry of your trial account and you don’t miss out any business in between.</div><div><br></div><div><b>Major clients who started with a free trial:&nbsp;</b></div><div><b><br></b></div><div><b>Arcelor Mittal Group, NMDC, Vedanta Group, Tata Steel, Citigroup, Sesa Goa, Essar Steel, Reliance ADAG, Aditya Birla Group, Essar Group, Rungta Mining Group, CRU Group</b> and many more.</div><div><br></div><div>For any support please feel free to contact me on +91 " . $RM_phoneno . ".</div><div><br></div><div><br></div><div>Have a great day!&nbsp;</div><div><br></div>
						<br /><br />
						Best regards<br /><span style=\"color:#666666\">
						" . $RM_name . "
						SteelMint Info Services LLP, India<br>
						ISO 9001:2008 Certified<br /><br /></span>
						<span style=\"color:#333333\"><br>
						**********************************************************************************************************<br />
						This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.<br /><br />
						**********************************************************************************************************<br /><br />
						SteelMint Info Services LLP, India<br />					
						";
						$attchFile = "/multipleattachmentmailphp/SteelMint - Product and Subscription Details_August13.pdf";
					}
					
					else
					{
						$sub = "SteelMint: Your Trial Account is expiring soon!";
						$name_ex = explode(" ", $name);
						$my_message .='<p>Dear '.$name_ex[0].',</p>';
						$my_message .='<p>Greetings..!</p>';
						$my_message .='<p>This is in regards to a trial that you registered on our portal - <a href="https://www.steelmint.com" target ="_blank">www.steelmint.com</a>. I hope you made good use of the data / information.</p>';
						$my_message .='<p>The services for one complete year are available at a cost of $550. This will give you access to the entire website and periodic reports on Iron ore, Coal, Scrap, Billet, Pig Iron, HR/CR, Rebars and Logistics among many other products. Have also attached product detail sheet for your reference.</p>';
						$my_message .='<p>Let me know if you need more information or support.</p><p>Feel free to write to me or chat with me on <strong>Skype: steelmint.india</strong>.</p><p>You can also call me on 0091 8269478280.</p>';
						$my_message .='<p><b>About SteelMint</b></p>';
						$my_message .='<p>SteelMint is the most premier steel research and data provider based in India. SteelMint boasts of a network of over 25,000 members involved in Steel across the globe. It is today servicing some of the largest business houses across the world for their requirement of steel data and related market intelligence. To name a few - Arcelor Mittal, BHP Billiton, Rio Tinto, Tata Steel, Jindal Steel, Deutsche Bank, Vedanta Group, NMDC Limited, Essar Group and many more companies of high repute.<br /></p>';
						$my_message .='<p>Hupendra Sahu | Overseas Sales<br />SteelMint Info Services LLP</p>';
						$my_message .='<p style="color:#606060;font-weight:bold; font-family:arial;font-size:small;">Handphone : +91 90393-22000 | Landline: +91 771 2284888<br />Email: <a target="_blank" style="color:rgb(42,93,176)" href="mailto:hupendra@steelmint.com">hupendra@steelmint.com</a> | Web: <a target="_blank" style="color:rgb(42,93,176)" href="https://www.steelmint.com/">www.steelmint.com</a><br />Linkedin: <a target="_blank" style="color:rgb(42,93,176)" href="https://www.steelmint.com/">https://www.linkedin.com/in/hupendraa </a> | Skype:steelmint.india </p>';
						$my_message .='<table><tr><td style="font-weight:normal;font-size:12px;border-collapse:collapse;color:rgb(0,0,128)"><font face=" sans-serif"> ******************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>**************************</font></td></tr>';
						$my_message .='<tr><td style="color:#000080;">This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.</td></tr>';
						$my_message .='<tr><td style="font-weight:normal;font-size:12px;border-collapse:collapse;color:rgb(0,0,128)"><font face=" sans-serif"> ******************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>**************************</font></td></tr></table>';
						$my_message .='<p style="color:#000080;margin:0;">SteelMint Info Services LLP., India</p>';					
						$attchFile = "/multipleattachmentmailphp/SteelMint - Product and Subscription Details_Overseas.pdf";
					}
				}
				else
				{
					$sub = "SteelMint: Your membership will expire within a week; Renew Now!";
					$my_message = '
					<div>Dear Mr. ' . $name . '</div><div><br />Greetings from SteelMint..!!</div><div><br></div><div>This is a small reminder to bring to your notice that your membership is expiring this week. We hope you are already in the process to renew your account.&nbsp;</div><div><br></div><div>In case you are not sure how to renew your account or want some help in choosing a right package, please feel free to approach me on +91 ' . $RM_phoneno . '.&nbsp;</div><div><br></div><div><b>For a hassle free renewal you can also renew your account online here:&nbsp;</b></div><div><a href="https://www.steelmint.com/memberegi">www.steelmint.com/memberegi</a></div><div><br></div><div>Please refer the attached SteelMint Product &amp; Subscription Detail Sheet for more details.</div><div><br></div><div>Look forward to your continuous patronage.&nbsp;</div><div><br></div><div>Have a great day!</div><div><br></div><br /><br />Best regards<br /><span style=\"color:#666666\">
					' . $RM_name . '
					SteelMint Info Services LLP, India<br>
					ISO 9001:2008 Certified<br /><br /></span>
					<span style=\"color:#333333\"><br>
					**********************************************************************************************************<br />
					This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.<br /><br />
					**********************************************************************************************************<br /><br />
					SteelMint Info Services LLP, India<br />
					';
				}
			}
			/*else
			{
				if($country != '113')
				{
					if($res['f_tenure'] == 'Free Trial')
					{
						$name_ex = explode(" ", $name);
						$my_message .='<p>Dear '.$name_ex[0].',</p>';
						$my_message .='<p>Greetings..!</p>';
						$my_message .='<p>This is in regards to a trial that you registered on our portal - <a href="https://www.steelmint.com" target ="_blank">www.steelmint.com</a>. I hope you made good use of the data / information.</p>';
						$my_message .='<p>The services for one complete year are available at a cost of $550. This will give you access to the entire website and periodic reports on Iron ore, Coal, Scrap, Billet, Pig Iron, HR/CR, Rebars and Logistics among many other products. Have also attached product detail sheet for your reference.</p>';
						$my_message .='<p>Let me know if you need more information or support.</p><p>Feel free to write to me or chat with me on <strong>Skype: steelmint.india</strong>.</p><p>You can also call me on 0091 8269478280.</p>';
						$my_message .='<p><b>About SteelMint</b></p>';
						$my_message .='<p>SteelMint is the most premier steel research and data provider based in India. SteelMint boasts of a network of over 25,000 members involved in Steel across the globe. It is today servicing some of the largest business houses across the world for their requirement of steel data and related market intelligence. To name a few - Arcelor Mittal, BHP Billiton, Rio Tinto, Tata Steel, Jindal Steel, Deutsche Bank, Vedanta Group, NMDC Limited, Essar Group and many more companies of high repute.<br /></p>';
						$my_message .='<p>Hupendra Sahu | Overseas Sales<br />SteelMint Info Services LLP</p>';
						$my_message .='<p style="color:#606060;font-weight:bold; font-family:arial;font-size:small;">Handphone : +91 90393-22000 | Landline: +91 771 2284888<br />Email: <a target="_blank" style="color:rgb(42,93,176)" href="mailto:hupendra@steelmint.com">hupendra@steelmint.com</a> | Web: <a target="_blank" style="color:rgb(42,93,176)" href="https://www.steelmint.com/">www.steelmint.com</a><br />Linkedin: <a target="_blank" style="color:rgb(42,93,176)" href="https://www.steelmint.com/">https://www.linkedin.com/in/hupendraa </a> | Skype:steelmint.india </p>';
						$my_message .='<table><tr><td style="font-weight:normal;font-size:12px;border-collapse:collapse;color:rgb(0,0,128)"><font face=" sans-serif"> ******************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>**************************</font></td></tr>';
						$my_message .='<tr><td style="color:#000080;">This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.</td></tr>';
						$my_message .='<tr><td style="font-weight:normal;font-size:12px;border-collapse:collapse;color:rgb(0,0,128)"><font face=" sans-serif"> ******************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>**************************</font></td></tr></table>';
						$my_message .='<p style="color:#000080;margin:0;">SteelMint Info Services LLP., India</p>';
					}
					else
					{
						$my_message = "
						Dear " . $name . " <br />
						" . $company . "<br />
						" . $res_city['name'] . "<br /><br />
						<i>Greetings from SteelMint..!!</i><br /><br />
						A quick reminder to tell you that your web service for " . $res['selected_products'] . " will expire on " . $expiry_date .".<br><br>
						To continue services with www.steelmint.com, please renew your subscription.<br>
						For more details reply to this email or contact me on +919575100530.<br />
						<br />
						Best regards<br /><span style=\"color:#666666\">
						" . $RM_name . "
						SteelMint Info Services LLP, India<br>
						ISO 9001:2008 Certified<br /><br /></span>
						<span style=\"color:#333333\"><br>
						************************************************************************************<br />
						This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.<br /><br />
						************************************************************************************<br /><br />
						SteelMint Info Services LLP, India<br />
						";
					}
				}	
			}*/
			if($exp == "Exp Today" || $exp == "Exp Bef a month" || $exp == "Exp Bef 7 days" || $exp == "Exp Bef 2 Days")
			{
				$test = new attach_mailer($name = str_replace("<br />", "", $RM_name), $from = $RM_email, $to = $email, $cc = "", $bcc = $RM_email, $subject = $sub, $body = $my_message);
//				if( !($res['f_tenure'] == 'Free Trial' && $exp == "Exp Bef a month") )
				{
					if( "" != $attchFile )
					{
						$mailAttachment_2 = DOCROOT . $attchFile;
						$test->create_attachment_part($mailAttachment_2);
					}
				}
				$test->process_mail();
			}				/*else
			{
				if($country != '113' && $country != '0' && $res['f_tenure'] == 'Free Trial')
				{
					$test = new attach_mailer($name = "Hupendra Sahu", $from = "hupendra@steelmint.com", $to = $email, $cc = "", $bcc = "hupendra@steelmint.com", $subject = "www.steelmint.com; your Trial service is active for 2 more days!", $body = $my_message);
					$mailAttachment = DOCROOT . "/multipleattachmentmailphp/SteelMint-Product_and_Subscription_Details_overseas.pdf";
					$test->create_attachment_part($mailAttachment);
					$test->process_mail();
				}
				else
				{
					$test = new attach_mailer($name = str_replace("<br />", "", $RM_name), $from = $RM_email, $to = $email, $cc = "", $bcc = $RM_email, $subject = 'www.steelmint.com; your web service is active for 2 more days!', $body = $my_message);
					$test->process_mail();
				}
			}*/
		}
	}
/*function intersted_to_pay()
{
	$currDate = $date->format( 'Y-m-d' );
	$tomorrow_date = date("Y-m-d",strtotime($currDate . '+1 days'));
	$dates = $currDate . ',' . $tomorrow_date;
	$sql_mem_reg_logs = "select id from tbl_reg_logs
						 where memid IN (
						   					select id from tbl_members where mood IN ('13')
										)
						 and f_tenure = 'Free Trial' and status = 'Active' and free_paid_dates = ''
						 and f_product IN ('W')
						 ";
	$res_members = mysql_query($sql_mem_reg_logs) or die(mysql_error());
	while($row_members = mysql_fetch_array($res_members,MYSQL_ASSOC))
	{
		$rs_update = mysql_query("update tbl_reg_logs set free_paid_dates = '" . $dates . "' where id='" . $row_members['id'] . "'");
	}
}*/

		function createMissingLogsInUpdatedRegLogTbl(){
			$service = array("W","S");
			$date  = date('Y-m-d H:i:s');
			foreach($service as $s)
			{
				$active_id = array();
				$all_id = array();
				$inactive_id = array();
				$query1 = mysql_query("SELECT distinct memid FROM `tbl_reg_logs` where f_product='$s' and status='Active'");
				while($row1 = mysql_fetch_assoc($query1))
				{
				   $active_id[] = $row1['memid'];
				}
				$query2 = mysql_query("SELECT distinct memid FROM `tbl_reg_logs` where f_product='$s'");
				while($row2 = mysql_fetch_assoc($query2))
				{
				   $all_id[] = $row2['memid'];
				}
				$inactive_id = array_diff($all_id,$active_id);
				
				if(count($inactive_id)>0)
				{
				  $mod ='';	     
				  if($s=='W')
					$mod = 'webservice';
				  
				  elseif($s=='S')
					$mod = 'smsservice';
				  
				  
				  foreach($inactive_id as $memid)
				  {
					 $qry = mysql_query("select * from `tbl_updated_reg_logs` where memid=$memid and services='$s'");
					 if(mysql_num_rows($qry)==0){		     
						  echo "<br />";
						  echo $final_query  = "INSERT INTO `tbl_updated_reg_logs` (`created_on`, `memid`, `services`, `paid_unpaid`, `status`, `active_products`, `nonactive_products`, `startdate`, `enddate`, `mod_srvc_name`) VALUES ('$date', '".$memid."', '$s', 'not_active', 'Inactive', '', '', '', '', '$mod');";
						   mysql_query($final_query);
						  //echo "<hr />";
					 }
				  }
				}
			
			}			
		}

function getDirectoryList ($directory, &$firstFileSmall, &$firstFileLarge, &$secondFileSmall, &$secondFileLarge)
{
    // create an array to hold directory list
    $results = array();
    // create a handler for the directory
    $handler = opendir($directory);
    // open directory and walk through the filenames
    while ($file = readdir($handler)) {
      // if file isn't this directory or its parent, add it to the results
      if ($file != "." && $file != "..") {
		if( strpos($file, "0_") !== false && strpos($file, "_small") !== false)
			$firstFileSmall = $file;
		if( strpos($file, "0_") !== false && strpos($file, "_large") !== false)
			$firstFileLarge = $file;
		if( strpos($file, "1_") !== false && strpos($file, "_small") !== false)
			$secondFileSmall = $file;
		if( strpos($file, "1_") !== false && strpos($file, "_large") !== false)
			$secondFileLarge = $file;
      }
    }
    // tidy up: close the handler
    closedir($handler);
}
function seoShuffle(&$items,$string)
{
    mt_srand(strlen($string));
    for ($i = count($items) - 1; $i > 0; $i--){
        $j = @mt_rand(0, $i);
        $tmp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $tmp;
    }
}
/*function shuffleTbl_shuffle()
{
	$sql_shuffle = "select *
					from tbl_shuffle
					";
	$res_shuffle = mysql_query($sql_shuffle);
	while($row_shuffle = mysql_fetch_array($res_shuffle,MYSQL_ASSOC))
	{
		$up[] = $row_shuffle['up'];
		$down[] = $row_shuffle['down'];
		$same[] = $row_shuffle['same'];
	}
	seoShuffle($up,'whatever');
	seoShuffle($down,'whatever');
	seoShuffle($same,'whatever');
	$sql_shuffle = "DELETE FROM tbl_shuffle";
	$res_shuffle = mysql_query($sql_shuffle);
	for($i = 0; $i < count($up); $i++ )
	{
		$sql = "insert into tbl_shuffle(up,down,same) values('" . $up[$i] . "','" . $down[$i] . "','" . $same[$i] . "')";
		$res = mysql_query($sql);
	}
}*/
/*
function shuffleTbl_item_rotation()
{
// =====================   code to shuffle tbl_item_rotation =====================
	$sql_shuffle = "SELECT distinct `raipur_type` FROM `tbl_fin` WHERE `f_type` = 'TMT' and `f_size` = '12MM'";
	$res_shuffle = mysql_query($sql_shuffle);
	while($row_shuffle = mysql_fetch_array($res_shuffle,MYSQL_ASSOC))
	{
		$place_TMT[] = $row_shuffle['raipur_type'];
	}
	$sql_shuffle = "SELECT distinct `f_place` FROM `tbl_fin` WHERE `f_type` = 'Angle' and `f_size` = '40/50/60/75 A'";
	$res_shuffle = mysql_query($sql_shuffle);
	while($row_shuffle = mysql_fetch_array($res_shuffle,MYSQL_ASSOC))
	{
		$place_Angle[] = $row_shuffle['f_place'];
	}
	$ran_number = array_rand($place_TMT, 1);
	$sql = "update tbl_item_rotation set shuffledPlace = '" . $place_TMT[$ran_number] . "' where id='1'";
	$res = mysql_query($sql);
	$ran_number = array_rand($place_Angle, 1);
	$sql = "update tbl_item_rotation set shuffledPlace = '" . $place_Angle[$ran_number] . "' where id='2'";
	$res = mysql_query($sql);
}*/
function generatePassword($length = 8) {
	$chars = '0123456789';
	$count = mb_strlen($chars);
	for ($i = 0, $result = ''; $i < $length; $i++) {
		$index = rand(0, $count - 1);
		$result .= mb_substr($chars, $index, 1);
	}
	return $result;
}
/**
 * This function will remove all the specified values from an array and return the final array.
 * Arguments :    The first argument is the array that should be edited
 *                The arguments after the first argument is a list of values that must be removed.
 * Example : array_remove_value($arr,"one","two","three");
 * Return : The function will return an array after deleting the said values
 */
function array_remove_value() {
    $args = func_get_args();
    $arr = $args[0];
    $values = array_slice($args,1);
    foreach($arr as $k=>$v) {
        if(in_array($v, $values))
            unset($arr[$k]);
    }
	$arr = array_values($arr);
    return $arr;
}
function getProdListFrmIdNew( $tbl_name, $id )
{
	$id = "'" . str_replace(",", "','", $id) . "'";
	$sql = "select GROUP_CONCAT(name) as prodList from $tbl_name where id IN ($id) ";
	$info = mysql_query($sql) or die(mysql_error());
	$row = mysql_fetch_array($info);
	return $row['prodList'];
}
/* function int_freetrail()
{
	//$currDate = $GLOBALS['currDate'];
	$startdate = date('Y-m-d',strtotime($GLOBALS['currDate'] . "-1 days"));
	$sql = "select rl.memid, tblm.name,tblm.email,tblm.relMngr
	from tbl_reg_logs as rl, tbl_members as tblm
	where rl.memid = tblm.id
	and tblm.country <> 113
	and rl.f_product = 'W'
	and rl.f_tenure like '%trial%'
	and rl.status = 'Active'
	and rl.startdate = '$startdate'
	and rl.comments <> 'activated ID of hupen template'
	";
	//and rl.startdate = DATE_SUB($currDate, INTERVAL 1 DAY)";
	$rsd = mysql_query($sql);
	while($row = mysql_fetch_array($rsd,MYSQL_ASSOC))
	{
		$memid = $row["memid"];
		$name = explode(" ", $row["name"]);
		$email = $row["email"];
		$relMngr = $row["relMngr"];
//		if($relMngr !='Hupendra Sahu')
		{
//						$tabRes ='';
			$tabRes .='<p>Dear '.$name[0].',</p>';
			$tabRes .='<p>Greetings from SteelMint..!</p>';
			$tabRes .='<p>I hope you are doing good.</p>';
			$tabRes .='<p>You happen to register a trial on our portal - <a href="https://www.steelmint.com" target ="_blank">www.steelmint.com</a> few days back. I am writing to check if you have proper access to the website and you were able to locate the desired data / information on the site.</p>';
			$tabRes .='<p>Please feel free to share your queries with me by emailing them or by chatting with me on <strong>Skype:steelmint.india</strong></p>';
			$tabRes .='<p>You can also call me on 0091 8269478280</p>';
			$tabRes .='<p>Best regards</p>';
			$tabRes .='<p>Amit Hablani</p>';
			$tabRes .='<p><b>About SteelMint</b></p>';
			$tabRes .='<p>SteelMint is the most premier steel research and data provider based in India. SteelMint boasts of a network of over 25,000 members involved in Steel across the globe. It is today servicing some of the largest business houses across the world for their requirement of steel data and related market intelligence. To name a few - Arcelor Mittal, BHP Billiton, Rio Tinto, Tata Steel, Jindal Steel, Deutsche Bank, Vedanta Group, NMDC Limited, Essar Group and many more companies of high repute.</p>';
			$tabRes .='<p>Amit Hablani | Overseas Sales<br />SteelMint Info Services LLP</p>';
			$tabRes .='<p style="color:#606060;font-weight:bold; font-family:arial;font-size:small;">Handphone : +91  86022-70907, | Landline: +91 771 4048884<br />Email: <a target="_blank" style="color:rgb(42,93,176)" href="mailto:amit.hablani@steelmint.com">amit.hablani@steelmint.com</a> | Web: <a target="_blank" style="color:rgb(42,93,176)" href="https://www.steelmint.com/">www.steelmint.com</a> | Skype:steelmint.india</p>';
$tabRes .='<table width="100%"><tr>
  <td style="font-weight:normal;font-size:12px;border-collapse:collapse;color:rgb(0,0,128)"><font face=" sans-serif"> ******************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>**********************************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>***************************************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>*</font></td>
</tr>
<tr><td style="color:#000080;">This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.</td></tr><tr><td style="font-weight:normal;font-size:12px;border-collapse:collapse;color:rgb(0,0,128)"><font face=" sans-serif">******************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>**********************************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>***************************************************<wbr></wbr>******************************<wbr></wbr>******************************<wbr></wbr>*</font></td>
</tr></table><p style="color:#000080;">SteelMint Info Services LLP., India</p>';
			//echo $tabRes;
			$sender_name = 'Amit Hablani';
			$sender_email = 'amit.hablani@steelmint.com';
			$headers = 'From:' . $sender_name . '<' . $sender_email . '>' . "\r\n" .
				'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
				'Bcc: amit.hablani@steelmint.com' . "\r\n" .
				'Reply-To: ' . $sender_email . "\r\n" .
				'X-Mailer: PHP/' . phpversion();
			mail($email, "SteelMint Support; Trial Service Related", $tabRes, $headers,"www.steelmint.com -f$sender_email");
			mysql_query("update tbl_members set relMngr = 'Amit Hablani' where  id =".$memid);
			mail("tarun@steelmint.com", "update relmngr for overseas clients to hablani", "update tbl_members set relMngr = 'Amit Hablani' where  id =".$memid, $headers,"www.steelmint.com -f$sender_email");
	}
} */
/*function activate_pankaj_karnataka_template_ids()
{
	$startdate = $GLOBALS['currDate'];
	$f_time = $GLOBALS['currTime'];
	$enddate  = date('Y-m-d', strtotime($startdate . '+14 days'));
	$created_date = $GLOBALS['currDate'] . " " . $GLOBALS['currTime'];
	$relMngr ='-NA-';
	$status ='Active';
	$f_product ='W';
	$f_tenure ='Free Trial';
	$selected_products ='Coal,FerroAlloy,FinishFlat,FinishLong,IronOre,Reports,Scrap,SemiFinished,steelnews';
	$query = "SELECT A.id as memid, A.name, A.username, A.password, A.email  FROM tbl_members A, tbl_reg_logs B where B.f_product='W' and B.enddate between '2012-04-01' and '2013-02-28' AND B.id = (SELECT max(D.id) from tbl_reg_logs as D where (D.memid = B.memid and D.f_product='W')) and A.mood IN ( 7,1,13,14,8,9 ) and A.state=12 and A.id = B.memid group by B.memid ORDER BY A.id limit 0,5";
	$res = mysql_query($query);
	$ids_list = '';
	while( $row = mysql_fetch_array( $res) )
	{
		$memid = $row['memid'];
		$sql_reg_logs = mysql_query("insert into tbl_reg_logs (memid,startdate,enddate,status,f_product,f_tenure,selected_products,f_time,comments,created_on) values ('$memid','$startdate','$enddate','$status','$f_product','$f_tenure','$selected_products','$f_time','activated ID of pankaj_karnataka template','$created_date')");
		$sql_members = mysql_query("update tbl_members set relMngr ='$relMngr', mood=0 where id='$memid'");
		$ids_list .= $memid . ",";
		$tabRes = '
		<div class="gmail_quote" style="color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 12.499999046325684px; background-color: rgb(255, 255, 255);"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div><b><font color="#222222" face="Arial, sans-serif">Dear "'. $row['name'] . '"</font><font color="#222222" face="Arial, sans-serif">,</font></b></div><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 12pt; font-family: \'Times New Roman\', serif;"></span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">&nbsp;</span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">Greetings from SteelMint.!</span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">&nbsp;</span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">It has been a long time that you visited our web portal&nbsp;<a href="https://www.steelmint.com/" target="_blank" style="color: rgb(17, 85, 204);">www.steelmint.com</a>.&nbsp;</span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;"><br></span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">We are happy to tell you that we have improved our coverage on Coal, Scrap, Ferro Alloys and Finished markets. Also we&nbsp;</span><span style="font-family: Arial, sans-serif; font-size: 13px;">have started covering many new markets and products including Import/Export statistics on various products.&nbsp;</span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;"><br></span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">Encouraged by the positive feedback from our existing clients we are offering&nbsp;</span><span style="font-size: 10pt; font-family: Arial, sans-serif;"><b>re-trials of our services for 14 days</b>&nbsp;to some of the clients like you. We hope that&nbsp;you too benefit from our services and get help on doing more business.&nbsp;</span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;"><br></span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;"><b>Username:</b>&nbsp;</span><b><font color="#222222" face="Arial, sans-serif">"'. $row['username'] . '"</font></b></p></div><div><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><b><span style="font-size: 10pt; font-family: Arial, sans-serif;">Password:</span></b><span style="font-size: 10pt; font-family: Arial, sans-serif;">&nbsp;</span><b><font color="#222222" face="Arial, sans-serif">"'. $row['password'] . '"</font></b></p><div><div><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><font color="#222222" face="Arial, sans-serif"><b>Link:&nbsp;</b><a href="https://www.steelmint.com/" target="_blank" style="color: rgb(17, 85, 204);">www.steelmint.com</a></font></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><font color="#222222" face="Arial, sans-serif"><br></font></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-family: Arial, sans-serif; font-size: 13px;">On this duration you shall be able to access all the information available on the website and will receive our news alerts and steel reports on your email ID.</span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><font color="#222222" face="Arial, sans-serif"><b><br></b></font></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><font color="#222222" face="Arial, sans-serif"><b>Note:&nbsp;</b>In case you do not want the 14 Days Trial, please reply back to this email with your concern.</font></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><b><span style="font-size: 10pt; font-family: Arial, sans-serif; color: white; background-color: rgb(204, 0, 0); background-position: initial initial; background-repeat: initial initial;"><br></span></b></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="background-color: rgb(255, 153, 0);"><b><span style="font-size: 10pt; font-family: Arial, sans-serif; color: white;">&nbsp;</span></b><b><span style="font-size: 10pt; font-family: Arial, sans-serif; color: white;">Quick Links:</span></b></span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">&nbsp;</span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">Steel Prices:&nbsp;</span><a href="https://www.steelmint.com/semifinished-ingot" target="_blank" style="color: rgb(17, 85, 204);">https://www.steelmint.<wbr>com/semifinished-ingot</a></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;"><br></span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">Steel News:&nbsp;</span><font color="#0000ee" face="Arial, sans-serif"><u><a href="https://www.steelmint.com/search_results-steelnews" target="_blank" style="color: rgb(17, 85, 204);">https://www.steelmint.<wbr>com/search_results-steelnews</a></u></font></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;"><br></span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">Import Export Statistics:&nbsp;</span><font color="#222222" face="Arial, sans-serif"><a href="https://www.steelmint.com/indian_import_export" target="_blank" style="color: rgb(17, 85, 204);">https://www.<wbr>steelmint.com/indian_import_<wbr>export</a></font></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-family: Arial, sans-serif; font-size: 10pt;">&nbsp;</span></p></div><div><div><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><b><span style="font-size: 10pt; font-family: Arial, sans-serif; color: white; background-color: rgb(255, 153, 0);">Set Your Email Preferences:</span></b><b><span style="font-size: 10pt; font-family: Arial, sans-serif; color: white;">&nbsp;</span></b><span style="font-size: 10pt; font-family: Arial, sans-serif;">You can set the number of emails you receive by visiting your profile &gt;&gt; Set Email Preferences. By default you will receive updates on all products.</span></p><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-size: 10pt; font-family: Arial, sans-serif;">&nbsp;</span></p></div><p class="MsoNormal" style="margin: 0px 0px 0.0001pt;"><span style="font-family: Arial, sans-serif; font-size: 10pt;">Should you like to discuss anything, feel free to reply back to me or call on +91 9993967907</span></p></div></div></div></div></div></div></div></div></div></div></div></div></div><p></p></div><br style="color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 12.499999046325684px; background-color: rgb(255, 255, 255);"><br style="color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 12.499999046325684px; background-color: rgb(255, 255, 255);"><div dir="ltr" style="color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 12.499999046325684px; background-color: rgb(255, 255, 255);"><div><span style="font-family: Calibri; font-size: 16px;">Thanks &amp; Regards,</span><br style="font-family: Calibri; font-size: 16px;"><br style="font-family: Calibri; font-size: 16px;"><font face="Calibri" size="3">Pankaj Namdev</font><br style="font-family: Calibri; font-size: 16px;"><span style="font-family: Calibri; font-size: 16px;">Asst. Manager - Marketing</span><br style="font-family: Calibri; font-size: 16px;"><font face="Calibri" size="3">STEELMINT INFO.SERVICES LLP</font><br></div><div><span style="font-family: Calibri; font-size: 16px;">Mob No : 09993967907</span><br style="font-family: Calibri; font-size: 16px;"><span style="font-family: Calibri; font-size: 16px;">E-Mail ID :&nbsp;</span><a href="mailto:kanodia@lancoindustries.com" target="_blank" style="color: rgb(17, 85, 204); font-family: Calibri; font-size: 16px;">pankaj.namdev@steelmint.com</a><br style="font-family: Calibri; font-size: 16px;"><span style="font-family: Calibri; font-size: 16px;">Website :&nbsp;</span><a href="https://www.lancoindustries.com/" target="_blank" style="color: rgb(17, 85, 204); font-family: Calibri; font-size: 16px;">www.steelmint.com</a></div><div><br></div><div><div>******************************<wbr>******************************<wbr>******************************</div><p></p><p>This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.</p><p>******************************<wbr>******************************<wbr>******************************</p><p>SteelMint Info Services LLP. India</p></div></div>
		';
		$sender_name = 'SteelMint';
		$sender_email = 'info@steelmint.com';
		$headers = 'From:' . $sender_name . '<' . $sender_email . '>' . "\r\n" .
			'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
			'Bcc: pankaj.namdev@steelmint.com' . "\r\n" .
			'Reply-To: ' . $sender_email . "\r\n" .
			'X-Mailer: PHP/' . phpversion();
		mail($row['email'], "SteelMint: Information that keeps you ahead on business!", $tabRes, $headers,"www.steelmint.com -f$sender_email");
	}
	$sender_name = 'SteelMint';
	$sender_email = 'info@steelmint.com';
	$headers = 'From:' . $sender_name . '<' . $sender_email . '>' . "\r\n" .
		'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
		'cc: sumit@steelmint.com' . "\r\n" .
		'Reply-To: ' . $sender_email . "\r\n" .
		'X-Mailer: PHP/' . phpversion();
	mail("pankaj.namdev@steelmint.com", "SteelMint: 5 Memids activated from pankaj's filter", $ids_list, $headers,"www.steelmint.com -f$sender_email");
}*/
/*
function activate_hupen_template_ids()
{
	$startdate = $GLOBALS['currDate'];
	$f_time = $GLOBALS['currTime'];
	$enddate  = date('Y-m-d', strtotime($startdate . '+14 days'));
	$created_date = $GLOBALS['currDate'] . " " . $GLOBALS['currTime'];
	$relMngr ='-NA-';
	$status ='Active';
	$f_product ='W';
	$f_tenure ='Free Trial';
	$selected_products ='Coal,FerroAlloy,FinishFlat,FinishLong,IronOre,Reports,Scrap,SemiFinished,steelnews';
	$query = "
		SELECT id as memid,
		       email,
		       username,
		       password,
		       name
		FROM tbl_members
		WHERE mood IN ('17',
				 '7',
				 '1',
				 '13',
				 '4',
				 '14',
				 '16',
				 '8',
				 '9',
				 '18')
		  AND country IN ('43',
				    '254')
		  AND id NOT IN
		  (
			select distinct memid
			from tbl_reg_logs
			where status = 'Active'
			and f_product IN ('W', 'S')
		  )
			order by id asc
		  limit 0,10
	";
	$res = mysql_query($query);
	$ids_list = '';
     $oneMonthBackDate = date('Y-m-d', strtotime($GLOBALS['currDate'] . "-30 days"));
	while( $row = mysql_fetch_array( $res) )
	{
		$memid = $row['memid'];
$sql_chk = "select memid from tbl_reg_logs where memid = '$memid' and f_product = 'W' and ( ( status = 'Active') OR (enddate >= '$oneMonthBackDate')  )";
$res_chk = mysql_query($sql_chk);
$row_chk = mysql_num_rows( $res_chk ) ;
if( $row_chk == 0 )
{
		$sql_reg_logs = mysql_query("insert into tbl_reg_logs (memid,startdate,enddate,status,f_product,f_tenure,selected_products,f_time,comments,created_on) values ('$memid','$startdate','$enddate','$status','$f_product','$f_tenure','$selected_products','$f_time','activated ID of hupen template','$created_date')");
		$sql_members = mysql_query("update tbl_members set relMngr ='$relMngr', mood=0 where id='$memid'");
		$ids_list .= $memid . ",";
		$tabRes = '
<div id=":2ui" style="overflow: hidden;"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div class="adM">
</div><div class="gmail_quote"><div><b><font color="#222222" face="Arial, sans-serif"><br>
</font></b></div>
<div><b><font color="#222222" face="Arial, sans-serif">Dear </font><font color="#222222" face="Arial, sans-serif">"'. $row['name'] . '",</font></b></div>
<div class="gmail_quote"><div class="gmail_quote"><div class="gmail_quote"><div><div><div><div>
<div><p class="MsoNormal" style="margin-bottom:0.0001pt"><span style="font-size:12.0pt;font-family:&quot;Times New Roman&quot;,&quot;serif&quot;"></span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">&nbsp;</span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">Greetings from
SteelMint.!</span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">&nbsp;</span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">It has been a long time that you visited our web portal <a href="https://www.steelmint.com" target="_blank">www.steelmint.com</a>.&nbsp;</span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222"><br></span></p><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial">
<span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">In the recent past we have improved our coverage on Coal, Steel Scrap, Ferro Alloys and Finished markets. Also we&nbsp;</span><span style="color:rgb(34,34,34);font-family:Arial,sans-serif;font-size:13px">have started new services like Tenders, Statistics, Weekly Market Tracker.&nbsp;</span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10pt;font-family:Arial,sans-serif;color:rgb(34,34,34)"><br></span></p><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial">
<span style="font-size:10pt;font-family:Arial,sans-serif;color:rgb(34,34,34)">To show you what improvements we have brought on our services, we are providing a</span><span style="font-size:10pt;font-family:Arial,sans-serif;color:rgb(34,34,34)"><b>&nbsp;14 day retrial </b>to you.&nbsp;</span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10pt;color:rgb(34,34,34);font-family:Arial,sans-serif"><br></span></p><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial">
<span style="font-size:10pt;font-family:Arial,sans-serif;color:rgb(34,34,34)"><b>Username:</b>&nbsp;</span><font color="#222222" face="Arial, sans-serif"><a href="mailto:naveen.korivi@essar.com" target="_blank">"'. $row['username'] . '"</a></font></p>
</div></div>
</div></div></div><div>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><b><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">Password:</span></b><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">&nbsp;</span><font color="#222222" face="Arial, sans-serif">"'. $row['password'] . '"</font></p>
<div>
<div>
<div><div><div><div>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><font color="#222222" face="Arial, sans-serif"><b>Link: </b><a href="https://www.steelmint.com" target="_blank">www.steelmint.com</a></font></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial">
<font color="#222222" face="Arial, sans-serif"><br></font></p><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="color:rgb(34,34,34);font-family:Arial,sans-serif;font-size:13px"><b>This Trial Period includes</b> - access to the website, free news alerts and steel reports.</span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><font color="#222222" face="Arial, sans-serif"><b><br></b></font></p><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial">
<font color="#222222" face="Arial, sans-serif"><b>Note: </b>In case you do not want the 14 Days Trial, please reply back with subject line "Deactivate" and we will do the needful.</font></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial">
<b><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:white;background:#cc0000"><br></span></b></p><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial">
<span style="background-color:rgb(255,153,0)"><b><span style="font-size:10pt;font-family:Arial,sans-serif;color:white">Quick
Links:</span></b></span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">&nbsp;</span></p>
<p class="MsoNormal" style="color:rgb(34,34,34);font-size:12px;margin-bottom:0.0001pt;font-family:arial,sans-serif"><span style="font-size:10pt;font-family:Arial,sans-serif">Steel Prices:&nbsp;</span><a href="https://www.steelmint.com/semifinished-ingot" style="color:rgb(17,85,204)" target="_blank">https://www.steelmint.<wbr>com/semifinished-ingot</a></p>
<p class="MsoNormal" style="color:rgb(34,34,34);font-size:12px;margin-bottom:0.0001pt;font-family:arial,sans-serif"><span style="font-size:10pt;font-family:Arial,sans-serif"><br></span></p>
<p class="MsoNormal" style="color:rgb(34,34,34);font-size:12px;margin-bottom:0.0001pt;font-family:arial,sans-serif"><span style="font-size:10pt;font-family:Arial,sans-serif">Steel News:&nbsp;</span><font color="#0000ee" face="Arial, sans-serif"><u><a href="https://www.steelmint.com/search_results-steelnews" style="color:rgb(17,85,204)" target="_blank">https://www.steelmint.<wbr>com/search_results-steelnews</a></u></font></p>
<p class="MsoNormal" style="color:rgb(34,34,34);font-size:12px;margin-bottom:0.0001pt;font-family:arial,sans-serif"><span style="font-size:10pt;font-family:Arial,sans-serif"><br></span></p>
<p class="MsoNormal" style="color:rgb(34,34,34);font-size:12px;margin-bottom:0.0001pt;font-family:arial,sans-serif"><span style="font-size:10pt;font-family:Arial,sans-serif">Import Export Statistics:&nbsp;</span><font color="#222222" face="Arial, sans-serif"><a href="https://www.steelmint.com/indian_import_export" style="color:rgb(17,85,204)" target="_blank">https://www.<wbr>steelmint.com/indian_import_<wbr>export</a></font></p>
</div></div></div><div><div><div><div>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">&nbsp;</span></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><b><span style="font-size:10pt;font-family:Arial,sans-serif;color:white;background-color:rgb(255,153,0)">Set
Your Email Preferences:</span></b><b><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:white">&nbsp;</span></b><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222">You can set the number of emails you receive by
visiting your profile &gt;&gt; Set Email Preferences. By default you will
receive updates on all products.</span></p><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:#222222"><br>
</span></p><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><b><span style="font-size:10pt;font-family:Arial,sans-serif;color:white;background-color:rgb(255,153,0)">Our Regular Clients:</span></b></p>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><br></p></div></div><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial">Kobe Steel, Tata Steel, Essar, RioTinto, BHP Bilitton, Noble Resources, Sun Coke, Glints Global, Priority International, European Metal Recycling Ltd, Vale International and many more.</p>
<div>
<p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial">
<b><span style="font-size:10pt;font-family:Arial,sans-serif;color:white;background-color:rgb(255,153,0)"><br></span></b></p><p class="MsoNormal" style="margin-bottom:0.0001pt;background-repeat:initial initial"><span style="font-size:10pt;color:rgb(34,34,34);font-family:Arial,sans-serif">Should you like to
discuss anything, feel free to reply back to me or call on 00 91&nbsp;</span><span style="font-size:13px;color:rgb(34,34,34);font-family:Arial,sans-serif">82694</span><span style="font-size:10pt;color:rgb(34,34,34);font-family:Arial,sans-serif">-78280.</span></p>
</div></div></div></div></div></div></div></div></div></div></div></div></div><p></p>
</div></div><div><div>--&nbsp;</div><p></p><p></p><div><div><div><div><div><div><div><div><div><div><div><div>Best Regards</div></div></div></div></div></div></div></div></div></div></div><div><div><b>Team SteelMint</b></div>
<div><span style="color:rgb(102,102,102)">SteelMint Info Services</span></div></div><div><div><font color="#666666">India\'s Premier Research Firm</font></div>
<div><font color="#666666"><br></font></div></div><div>
<div><b><font color="#666666">Contact</font></b>: +91 95751-00530, +91 9575100430 &nbsp;|&nbsp;<b><font color="#666666">E-mail: </font></b><a href="mailto:info@steelmint.com" target="_blank">info@steelmint.com</a></div>
<div><span style="font-family:verdana,\'Trebuchet MS\',Arial,Helvetica,sans-serif;font-size:12px"><br></span></div><div><span style="font-size:12px"><font face="arial, helvetica, sans-serif">Connect with us on&nbsp;</font></span>Skype: steelmint.india | <a href="https://www.steelmint.com/aboutus" target="_blank">About SteelMint?</a></div>
<div>
<div><b><br></b></div><div>******************************<wbr>******************************<wbr>******************************</div><p></p><p>This e-mail contains information and/or attachment(s) that may be confidential and are intended for the exclusive use of the addressee(s). If you are not the intended recipient, you should not use, disclose, copy or take any action based on this message. If this e-mail has been received by you in error, please notify the sender immediately and delete this e-mail/attachment(s) from your system.</p>
<p>******************************<wbr>******************************<wbr>******************************</p><p>SteelMint Info Services LLP. India</p></div></div></div></div></div></div></div></div><div class="yj6qo"></div><div class="adL"><p></p>
</div></div><div class="adL"><br><br clear="all"></div><div class="adL"><br></div><div class="adL">
</div></div>
		';
		$sender_name = 'SteelMint';
		$sender_email = 'info@steelmint.com';
		$headers = 'From:' . $sender_name . '<' . $sender_email . '>' . "\r\n" .
			'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
			'Bcc: tarun.goel22@gmail.com' . "\r\n" .
			'Reply-To: ' . $sender_email . "\r\n" .
			'X-Mailer: PHP/' . phpversion();
		mail($row['email'], "SteelMint: Information that helps you do more business!", $tabRes, $headers,"www.steelmint.com -f$sender_email");
}
	}
	$sender_name = 'SteelMint';
	$sender_email = 'info@steelmint.com';
	$headers = 'From:' . $sender_name . '<' . $sender_email . '>' . "\r\n" .
		'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
		'cc: sumit@steelmint.com' . "\r\n" .
		'Reply-To: ' . $sender_email . "\r\n" .
		'X-Mailer: PHP/' . phpversion();
	mail("amit.hablani@steelmint.com", "SteelMint: 10 Memids activated from hupendra's filter", $ids_list, $headers,"www.steelmint.com -f$sender_email");
	mail("hupendra@steelmint.com", "SteelMint: 10 Memids activated from hupendra's filter", $ids_list, $headers,"www.steelmint.com -f$sender_email");
	mail("tarun@steelmint.com", "SteelMint: 10 Memids activated from hupendra's filter", $ids_list, $headers,"www.steelmint.com -f$sender_email");
}
*/
// ======================  calling function for interested to pay clients (to show dem all website rows) =================
//intersted_to_pay();
	function cMntMailer($date, $mntName)
	{
		$q = "
			select tm.email, tm.id, 
			case 
				when tm.billing_name <> '' 
				then tm.billing_name
				else  tm.name
			end  as name
			from
			(
				SELECT memid, max(id) as maxId,  group_concat(status) as st
				FROM `tbl_reg_logs`
				where f_product = 'M'
				and f_tenure not like 'free%'
				group by memid
				having (st <> 'Active' AND st NOT like 'Active,%' AND st NOT like '%,Active,%' AND st NOT like '%,Active' and st like '%Expired%') 
			) as res1,
			
			tbl_members as tm, tbl_reg_logs as trl
			
			where tm.id = res1.memid
			AND trl.id = res1.maxId
			AND trl.issues_to_go like '".$mntName."%'
		";					
		$rs = mysql_query($q);
		$arr= array(); $expiringMemids = '';
		while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
		{
			$expiringMemids .= $row['id'] . ",";
			$arr[] = $row;
		}
		
		$expiringMemids = trim($expiringMemids, ",");
		if('' != $expiringMemids){
			$ex = explode(",", $expiringMemids); $finStr = '';
			for( $i = 0; $i < count($ex); $i++ ){
					$finStr .= "<a href = 'https://www.steelmint.com/steeladmin/magazine_member.php?id=" . $ex[$i] . "'>" . $ex[$i] . "</a>, ";
			}		
			$content = "
				Paid log of following memids is expiring this month: <br /><br />
				$finStr
			";		
			sendSMMail($content, "kapil@steelmint.com,leena@steel-360.com", '', "Steel360: Paid logs expiring this month!!");		
		}	
		sendMailer($date, $mntName, 'CURRENT', $arr);
	}

	function nMntMailer($date, $mntName)
	{
		$q = "
			select tm.email, tm.id, 
			case 
				when tm.billing_name <> '' 
				then tm.billing_name
				else  tm.name
			end  as name
			from
			(
				SELECT memid, max(id) as maxId
				FROM `tbl_reg_logs`
				where f_product = 'M'
				and status = 'Active'
				and f_tenure not like 'free%'
				group by memid
			) as res1,
			
			tbl_members as tm, tbl_reg_logs as trl
			
			where tm.id = res1.memid
			AND trl.id = res1.maxId
			AND trl.issues_to_go like '".$mntName."%'		
		";
		
		$rs = mysql_query($q);
		$arr= array();
		while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
		{
			$arr[] = $row;
			$expiringMemids .= $row['id'] . ",";
		}
		
		$expiringMemids = trim($expiringMemids, ",");
		if('' != $expiringMemids){
			$ex = explode(",", $expiringMemids); $finStr = '';
			for( $i = 0; $i < count($ex); $i++ ){
					$finStr .= "<a href = 'https://www.steelmint.com/steeladmin/magazine_member.php?id=" . $ex[$i] . "'>" . $ex[$i] . "</a>, ";
			}		
			$content = "
				Paid log of following memids is expiring NEXT month: <br /><br />
				$finStr
			";		
			sendSMMail($content, "kapil@steelmint.com,leena@steel-360.com", '', "Steel360: Paid logs expiring NEXT month!!");
		}
		
		sendMailer($date, $mntName, 'NEXT', $arr);
	}

	function pMntMailer($date, $mntName)
	{
		$q = "
			select tm.email, tm.id, 
			case 
				when tm.billing_name <> '' 
				then tm.billing_name
				else  tm.name
			end  as name
			from
			(
				SELECT memid, max(id) as maxId,  group_concat(status) as st
				FROM `tbl_reg_logs`
				where f_product = 'M'
				and f_tenure not like 'free%'
				group by memid
				having (st <> 'Active' AND st NOT like 'Active,%' AND st NOT like '%,Active,%' AND st NOT like '%,Active' and st like '%Expired%') 
			) as res1,
			
			tbl_members as tm, tbl_reg_logs as trl
			
			where tm.id = res1.memid
			AND trl.id = res1.maxId
			AND trl.issues_to_go like '".$mntName."%'
		";					
				
		$rs = mysql_query($q);
		$arr= array(); $expiringMemids = '';
		while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
		{
			$arr[] = $row;
			$expiringMemids .= $row['id'] .  ",";
		}
		$expiringMemids = trim($expiringMemids, ",");
		if('' != $expiringMemids){
			$ex = explode(",", $expiringMemids); $finStr = '';
			for( $i = 0; $i < count($ex); $i++ ){
					$finStr .= "<a href = 'https://www.steelmint.com/steeladmin/magazine_member.php?id=" . $ex[$i] . "'>" . $ex[$i] . "</a>, ";
			}		
			$content = "
				Paid log of following memids has expired last month: <br /><br />
				$finStr
			";		
			sendSMMail($content, "kapil@steelmint.com,leena@steel-360.com", '', "Steel360: Paid logs has expired last month!!");			
		}	
		sendMailer($date, $mntName, 'PREV', $arr);
	}

	function sendMailer($date, $mntName, $mnt, $members=array())
	{
		$bcc = '';
		foreach($members as $mem){
			$name = $mem['name'];
			$memid = $mem['id'];
			
			$r = mysql_query("
				select max(id)  as maxMgzId
				from tbl_mgz_address
				where memid = '$memid'
			");
			$r1 = mysql_fetch_array($r);
			$mgzId = $r1['maxMgzId'];
			$url = "https://www.steel-360.com/subscribenow.php?renew=1&memid=" . $memid . "&mgzId=" . $mgzId;
			
			switch ($mnt)
			{
				case 'CURRENT':
					$d = date("d", strtotime($date));
					$my = date("F, Y", strtotime($date));
					$m = date("F", strtotime($date . ' +1 months'));
					
					$valArr = array(
								'name'=>$name,
								'month'=>$m,
								'url'=>$url,
								'month_year'=>$my,
							);
					
					if ($d == 21)
					{
						$emailTemplate = getEmailTemplate(2003);
						$sub_txt = $emailTemplate[1]['sub_txt'];
						$msgs =  getActualMailBody($emailTemplate, $valArr);
					}
				    else
					{
						$emailTemplate = getEmailTemplate(2004);
						$sub_txt = $emailTemplate[1]['sub_txt'];
						$msgs =  getActualMailBody($emailTemplate, $valArr);
					}

					break;

				case 'NEXT':
					$d = date("d", strtotime($date));
					$my = date("F, Y", strtotime($mntName));
					$m = date("F", strtotime($mntName));
					
					$valArr = array(
								'name'=>$name,
								'month'=>$m,
								'url'=>$url,
								'month_year'=>$my,
							);
					
					if ($d == 21)
					{
						$emailTemplate = getEmailTemplate(2005);
						$sub_txt = $emailTemplate[1]['sub_txt'];
						$msgs =  getActualMailBody($emailTemplate, $valArr);
					}
				    else
					{
						$emailTemplate = getEmailTemplate(2006);
						$sub_txt = $emailTemplate[1]['sub_txt'];
						$msgs =  getActualMailBody($emailTemplate, $valArr);
					}

					break;

				case 'PREV':
					$d = date("d", strtotime($date));
					$my = date("F, Y", strtotime($mntName));
					$m = date("F", strtotime($date));
					$valArr = array(
								'name'=>$name,
								'month'=>$m,
								'url'=>$url,
								'month_year'=>$my,
							);
					if ($d == 5)
					{
						$emailTemplate = getEmailTemplate(2007);
						$sub_txt = $emailTemplate[1]['sub_txt'];
						$msgs =  getActualMailBody($emailTemplate, $valArr);
						$sub_txt = str_replace("%recipient.month%", date("F"), $sub_txt);
					}
					else
					{
						$emailTemplate = getEmailTemplate(2008);
						$sub_txt = $emailTemplate[1]['sub_txt'];
						$msgs =  getActualMailBody($emailTemplate, $valArr);
					}

				break;
			}
			$a = sendSMMail($msgs, $mem['email'] . ",subscriptions@steel-360.com", "Steel360", $sub_txt, "", "subscriptions@steel-360.com", "Steel 360 Magazine", "subscriptions@steel-360.com");	
		}
	}
/* 	
function activateIdsCreatedfromExcel()
{
	$comments = 'by hupendra excel sheet';
	$currDate = $GLOBALS['currDate'];
	$currTime = $GLOBALS['currTime'];
	$currDateTime = $GLOBALS['currDateTime'];
	$sql= "select GROUP_CONCAT(f_product) as f_products  from tbl_product_items where  web_sms in ('W')  and f_product<>'Reports' order by web_sms desc";				
	$rs = mysql_query($sql);
	$selected_products_web_arry='';
	$row = mysql_fetch_array($rs);
	$selected_products_web = trim($row['f_products']);
	
	$memSql = "
				select res1.* 
				from
				(
					SELECT id as memid, 'D' as rgn, alternate_mob_no
					FROM  tbl_members 
					where comments='by hupendra excel sheet' 
					and country = 113
					order by id asc 
					limit 3
				) as res1	
				
				UNION
				
				select res2.* 
				from
				(
					SELECT id as memid, 'I' as rgn, alternate_mob_no
					FROM  tbl_members 
					where comments='by hupendra excel sheet' 
					and country <> 113
					order by id asc 
					limit 2
				) as res2	
			  ";
	$rsMem = mysql_query($memSql);
	while($row = mysql_fetch_array($rsMem)){
		$memid = $row['memid'];
		$rgn  = $row['rgn'];
		$alternateMobNo = $row['alternate_mob_no'];
		
		$status = "Active";
		
		$expiry_web  = date('Y-m-d', strtotime($currDateTime . '+14 days'));
		$subscriptionid_web = "Free Trial";
		
		///web log
	$inserQry ="insert into tbl_reg_logs (f_time, memid, startdate, enddate, status, f_product, f_tenure,  selected_products, prev_freeTrial, created_on, comments) values('$currTime', '$memid', '$currDate', '$expiry_web', '$status','W', '$subscriptionid_web', '$selected_products_web', '$selected_products_web', '$currDateTime', '$comments')";
		
		mysql_query($inserQry) or die(mysql_error());
		///tenders log
		$expiry_web  = date('Y-m-d', strtotime($currDateTime . '+30 days'));
	$inserQry1 ="insert into tbl_reg_logs (f_time, memid, startdate, enddate, status, f_product, f_tenure,  selected_products, prev_freeTrial, created_on, tenders_group, tenders_w_s, comments) values('$currTime', '$memid', '$currDate', '$expiry_web', '$status','T', '$subscriptionid_web', 'TENDERS', '', '$currDateTime', '$selected_products_web', 'W,S', '$comments')";
		mysql_query($inserQry1) or die(mysql_error());
		
		$comm = "Marketing Trial Started on: $currDate ";
		if( "D" == $rgn )
			mysql_query("
				insert into tbl_comments ( memid, f_date, f_time, comments, created_by, comments_for)
				values ('$memid', '$currDate', '$currTime', '$comm', 'SM', 'W');
			") or die(mysql_error());
		else
		{
			$alternateMobNo = $comm . $alternateMobNo;			
			mysql_query("
				insert into tbl_comments ( memid, f_date, f_time, comments, created_by, comments_for)
				values ('$memid', '$currDate', '$currTime', '$alternateMobNo', 'SM', 'W');
			") or die(mysql_error());
		}
		mysql_query("update tbl_members set comments='" . $comments. ' "done on '.$currDate.' "' . "' where id='$memid'"); 
	}
}	
 */
function sendSignsSMSToNewUser()
{
	$currDate = $GLOBALS['currDate'];
$msg='Dear Patron

Below are the signs used on SteelMint prices

Advance Payment (*)
Basic Prices (++)
Including ED (+)
Including all (#)

For more support
9575100530

Mob App www.goo.gl/cjMh7L
	';
	$date1  = date('Y-m-d',strtotime($currDate.'-1 days'));
	$date2  = date('Y-m-d',strtotime($currDate.'-2 days'));
	$date3  = date('Y-m-d',strtotime($currDate.'-3 days'));
	
	$q1   = "SELECT CASE
			   WHEN send_sms_to = 'A' THEN m.alternate_mob_no
			   ELSE phoneno
			END as phone
			FROM `tbl_reg_logs` r, tbl_members m 
			WHERE r.memid=m.id 
			AND ( r.startdate IN ('$currDate', '$date1', '$date2') OR (r.startdate = '$date3' AND r.f_time > '10:00:00')) 
			AND r.f_product = 'S'
			AND r.status = 'Active'
			";
	$rs1 = mysql_query($q1);
	if(mysql_num_rows($rs1) > 0)
	{	
		$pMobNos='';
		while($row = mysql_fetch_array($rs1,MYSQL_ASSOC))
		{
			if($row['phone'])
			{
				if($pMobNos != '')
					$pMobNos.=',';
				$pMobNos.=$row['phone'];
			}
					
		}
		//echo $pMobNos;
		if('' != $pMobNos)
			sendBULKsms($pMobNos,$msg);
	}
}
	
	
	function getSHanghaiData()
	{
		$d = date("Ymd");
		$url = "https://www.shfe.com.cn/data/dailydata/kx/kx$d.dat?isAjax=true";
		$json = file_get_contents($url);
		$json_data = json_decode($json, true);
		//echo print_r($json_data);

		$max=0;$close='';
		foreach($json_data['o_curinstrument'] as $k=>$prod){
			if(trim($prod['PRODUCTID'])=='rb_f' && $prod['VOLUME']>0){		
				if(intval($prod['VOLUME']) > $max && !empty($prod['CLOSEPRICE'])){
					$close = $prod['CLOSEPRICE']; 
					$max = intval($prod['VOLUME']);
				}
			}
		}
		return $close;	
	}
	
	function getCMEData()
	{
		$path = "https://www.cmegroup.com/trading/metals/ferrous/hrc-steel.html";
		$code = file_get_contents($path);
		$exp  = explode('_priorSettle">',$code);
		$exp1 = explode("</td>",$exp[1]);
		return  $exp1[0];
	}
	
	function getUSD_to_INRData()
	{
		include('simple_html_dom.php');
		$html = file_get_html('https://www.xe.com');
		foreach($html->find('a[rel=INR,USD,1,4]') as $e)
			return $num_total = $e->innertext;
	}
	
	
function get_curl_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

 if ($con_obj) mysql_close($con_obj);
 include "/home/steelmin/public_html/inc/desconfig.php";
?>