<?php

if (
    isset($_REQUEST['plancode']) && $_REQUEST['plancode'] != '' &&
    ((isset($_REQUEST['token']) && $_REQUEST['token'] != '') ||
    (isset($_REQUEST['member_id']) && $_REQUEST['member_id'] != ''))
){
	include ('/home/steelmin/public_html/inc/config1.php');
	include ('/home/steelmin/public_html/hf.php');
	include ('/home/steelmin/public_html/mf.php');
	include ('/home/steelmin/public_html/steeladmin/hf_360.php');
    //if($request->has('plancode'))
    {
    	 if(isset($_REQUEST['type']))
    		$type = $_REQUEST['type'];	
    	if(isset($_REQUEST['member_id']))
    		$member_id = $_REQUEST['member_id'];	
    	if(isset($_REQUEST['token'])){
    		$token = $_REQUEST['token'];	
			$member_id = 0 ;
			$c_at = date("Y-m-d H:i:s");
			
			if( $token != '' ){
				$a = mysql_query("select * from tokens where token = '$token' ");
				if( mysql_num_rows($a) > 0 ){
					$b = mysql_fetch_array($a);
					$member_id = $b['id'] ;	
				} else {
					echo 'Unauthorized action. Token access denied';
					include ('/home/steelmin/public_html/inc/desconfig.php');
					die;
				}
			}
		}
    	if(isset($_REQUEST['currency']))
    		$currency = $_REQUEST['currency'];	
    	if(isset($_REQUEST['price']))
    		$price = $_REQUEST['price'];	
    	sendVerifymail_new($member_id, 'www.steelmint.com');
		$gvFreeTrial = 0;
    	if( $type == 'Free Trial' ){
           ///chk any records is -> active for mobile and both Active and Expired for others
            $val  = qryToCommaSepString("
    				SELECT enddate
    				from tbl_reg_logs
    				where memid = $member_id
    				AND  status IN ( 'Active',  'Expired' )
    				AND f_product IN ( 'MA', 'W' )
					order by enddate desc
					limit 0,1
    			");//AND status in ($status_in) AND f_tenure = 'Free Trial'
            if( '' != $val ){
				$date1=date_create($val);
				$date2=date_create(date("Y-m-d"));
				$diff=date_diff($date1,$date2);
				$df = $diff->format("%a");
				if($df < 90) {
					//echo "You can't take Free Trial this time.";
					echo '<html><head><meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
					</head><body><div style="width:90%;margin:auto;">
					<p style="text-align:center;font-size:31px;font-weight:bold;font-family:arial">SORRY!</p>
					<p style="text-align:center;font-size:21px;"><img src="../../images/app/sad_face.png" alt="" /></p>
					<p style="font-size:16px;">This email has either active service or earlier taken service.</p>
					<p style="font-size:16px;">We have emailed SteelMint credentials to you. Kindly use them to login to our APP</p>
					</div></body></html>';
					$a = mysql_query("
						select case 
									when send_email_to = 'R' then email 
									else addtnl_email 
								end as clientEmail, 
								relMngr, 
								(select RM_email from tbl_rel_manager where rel_manager = tbl_members.relMngr)  as rmEmail
						from tbl_members 
						where id = $member_id 
					");
					$b = mysql_fetch_array($a);
					forgotPassword($b["clientEmail"]) ;
					
					sendSMMail($msgs="memid: <a href='https://www.steelmint.com/steeladmin/webservice.php?id=$member_id'> $member_id </a> <br /> trying to re take free trial. Has been denied to him.", $b["rmEmail"] . ",info@steelmint.com", $name_to_email_cc="", $subject="SteelMint Mobile App: Client re-trying to take free trial", $attachment="", $from_email="info@steelmint.com", $from_name="SteelMint", $reply_to="info@steelmint.com");					
				} else 
					$gvFreeTrial = 1;
            } else {   	
				$gvFreeTrial = 1;
            }	  

			if($gvFreeTrial == 1){
				$start_date= date("Y-m-d");
				$end_date=date("Y-m-d",strtotime("$start_date +14 days"));
				$arr['tbl_reg_logs']=array(
					'memid'=>$member_id,
					'startdate'=>$start_date,
					'enddate'=>$end_date,
					'f_time'=>$GLOBALS['currTime'],
					'f_product'=>'MA',
					'f_tenure'=>'Free Trial',
					'status'=>'Active',
					'selected_products'=>"Mobile App",
					'comments'=>"from mobile app",
					'created_on'=>date("Y-m-d H:i:s")
				);	
				 $r = create_logs_from_array_of_array($arr);
				 updateTbltbl_updated_reg_logs($member_id);
				echo '<html><head><meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
					</head><body><div style="width:90%;margin:auto;">
					<p style="text-align:center;font-size:31px;font-weight:bold;font-family:arial">THANK YOU!</p>
					<p style="text-align:center;font-size:21px;"><img src="../../images/app/success.png" alt="" /></p>
					<p style="font-size:16px;">Your <b>Free Trial</b> service has been activated. Kindly <b>Login</b>.</p>
					<p style="font-size:16px;">We have emailed you a verification link. Kindly click on that to activate your account and come back and login to our APP.</p>
					<p style="font-size:16px;">Please contact on below details for further information.</p>
					<p style="font-size:16px;"><strong>Email:</strong> info@steelmint.com<br><strong>Phone:</strong> +91 9770056666</p>
				</div></body></html>';
				$email =  qryToCommaSepString("select case when send_email_to = 'R' then email else addtnl_email end as email from tbl_members where id = $member_id ");				
			}
    	} elseif( $type == 'Paid' || $type == 'Renew'){
    	    if($_REQUEST['plancode'] == 'ios'){
    	        $received_thru = "ios";
    	        $order_id = '';
    	    } else {
    			$order_id = getSMorderNoForCCAVENUE("SM");
    
    			include_once("/home/steelmin/public_html/sm_group_events/regProcess/paypal_country.php");
    			$ip_countryName = qryToCommaSepString("
    				select country 
    				from tbl_country 
    				where id in ( 
    					select country 
    					from tbl_members 
    					where id=$member_id
    				)
    			"
    			);
    			
    			if( $currency == "USD"){
    				if(in_array(strtoupper($ip_countryName), $_paypal_country)){
    					$pymtURLToredirectTo =  "https://www.steelmint.com/paypal/payment.php";
    					$received_thru = "Paypal";
						$price= 225;
    				} else {
    					$pymtURLToredirectTo =  "https://www.steelmint.com/pay/newCheckOut.php";
    					$received_thru = "CCAvenue - International";
						$price=225;
    				}	
    			} else {
    				$received_thru = "CCAvenue - Domestic";
    				$pymtURLToredirectTo = "https://www.steelmint.com/pay/newCheckOut.php";
					$price=12500;
    			}				        
    	    }
			$_renew='';
			if($member_id==56350 || $member_id==77302 || $member_id==83757)
				$price=1;
			/* if(strtolower($type)=='renew'){
				$enddate  = qryToCommaSepString("
    				SELECT enddate
    				from tbl_updated_reg_logs
    				where memid = $member_id
    				AND status = 'Active'
    				AND paid_unpaid = 'paid'
    				AND services IN ( 'MA', 'W' )    
    			");
				if($enddate)
					$start_date=date("Y-m-d",strtotime("$enddate +1 days"));
				else
					$start_date= date("Y-m-d");
			}else
				$start_date= date("Y-m-d"); */
			$enddate  = qryToCommaSepString("
    				SELECT enddate
    				from tbl_updated_reg_logs
    				where memid = $member_id
    				AND status = 'Active'
    				AND paid_unpaid = 'paid'
    				AND services IN ( 'MA', 'W' )    
    			");
				if($enddate)
					$start_date=date("Y-m-d",strtotime("$enddate +1 days"));
				else
					$start_date= date("Y-m-d");
				
    		$end_date=date("Y-m-d",strtotime("$start_date +365 days"));
    		$arr['tbl_reg_logs']=array(
    			'memid'=>$member_id,
    			'startdate'=>$start_date,
    			'enddate'=>$end_date,
    			'f_time'=>$GLOBALS['currTime'],
    			'f_product'=>'MA',
    			'f_tenure'=>'One Year',
    			'status'=>'Pending',
    			'selected_products'=>"Mobile App",
    			'comments'=>"from mobile app",
    			'amtPaid'=>$price,
    			'created_on'=>date("Y-m-d H:i:s"),
    			'received_thru' => $received_thru,
    			'billNo' => $order_id,
    			'card_category' => $currency
    		);
    		
    		$r = create_logs_from_array_of_array($arr);
    		$_log_id = $r['tbl_reg_logs'];
    		//$price = 1; //for testing; remove this line
    		 if($_REQUEST['plancode'] == 'ios'){
    		    $result["log_id"] = $_log_id;     
    		    echo json_encode($result); 
    		 } else {
    			if( $pymtURLToredirectTo ==  "https://www.steelmint.com/pay/newCheckOut.php" )
    				header("Location:" . $pymtURLToredirectTo . "?reglogs_id=$_log_id&uid=$member_id&pymtSrc=mobileapp&productPurchased=MOB_APP&amt=$price&currency=$currency&orderid=$order_id");
    			else
    				header("Location:" . $pymtURLToredirectTo . "?reglogs_id=$_log_id&uid=".$member_id."&pymtSrc=mobileapp&item_desc=Payment for Order :".$order_id."&amt=".$price."&output=embed");
    		 }
    	} /* elseif( $type == 'Renew' ){
    		if($request->has('token'))
    		{
    			$token = $request->input('token');
    			$auth = new authentication();
    
    			$member_id = $auth->authToken($token);
    			if(!$member_id)
    				abort(403, "Unauthorized action. Token access denied") ;
    			else{
    				return "Renew:" . 1234;
    			}
    		} else
    			abort(403, "Unauthorized action. Token access denied") ;
    	} */ else {
    	    echo "Some issue!!";
    	    
    	}    
    } 
    include ('/home/steelmin/public_html/inc/desconfig.php');
    die;
}			

if (isset($_REQUEST['FCM_tag']) && $_REQUEST['FCM_tag'] == 'FCM'){
	include ('/home/steelmin/public_html/inc/config1.php');

	$token 			 	= $_REQUEST['token']; //if user is logged in then send memid / token.
	$device_id 			= $_REQUEST['device_id']; //if user is logged in then send memid / token.
	$device 			= $_REQUEST['device']; //if user is logged in then send memid / token.
	$physical_id 		= $_REQUEST['physical_id']; //if user is logged in then send memid / token.
	$FCM_tag 			= $_REQUEST['FCM_tag']; //if user is logged in then send memid / token.
	
	$user_id = 0 ;
	$c_at = date("Y-m-d H:i:s");
	
	if( $token != '' ){
		$a = mysql_query("select * from tokens where token = '$token' ");
		if( mysql_num_rows($a) > 0 ){
			$b = mysql_fetch_array($a);
			$user_id = $b['id'] ;	
		} else {
			echo 'Unauthorized action. Token access denied';
			include ('/home/steelmin/public_html/inc/desconfig.php');
			die;
		}
	}

	if( $device_id == '' && $device == ''){
		echo 'Partial Input, device accepted value (android/ios)';
		include ('/home/steelmin/public_html/inc/desconfig.php');
		die;
	}

	$a = mysql_query("select * from gcm_device where device_id = '$device_id' and device = '$device' order by id limit 0,1 ");
	if( mysql_num_rows($a) > 0 ){
		$b = mysql_fetch_array($a);
		$id = $b['id'] ;	
		$user_id_in_db = $b['user_id'] ;	
		if( $user_id_in_db == 0 && $user_id == 0 ){//user NOT logged in
			//do nothing
		} else if( $user_id_in_db == 0 && $user_id != 0 ){//user logs in
			mysql_query("update gcm_device set user_id = $user_id, FCM_tag='$FCM_tag'  where id = $id  ");
		} else if( $user_id_in_db == $user_id ){
			//user already logged in; do nothing
		} else if( $user_id_in_db != $user_id ){//multi login;
			mysql_query("update gcm_device set user_id = $user_id, FCM_tag='$FCM_tag'  where id = $id  ");
			/* mysql_query("delete from gcm_device where device_id = '$device_id' and device = '$device' ") or die (mysql_error());
			mysql_query("insert into gcm_device (device, device_id, FCM_tag, created_at, user_id, physical_id)
				values ('$device', '$device_id', '$FCM_tag', '$c_at', $user_id, '$physical_id')") or die (mysql_error()); */
		}
	} else {
		mysql_query("insert into gcm_device (device, device_id, FCM_tag, created_at, user_id, physical_id)
			values ('$device', '$device_id', '$FCM_tag', '$c_at', $user_id, '$physical_id')") or die (mysql_error());
		$id = mysql_insert_id();
	}
	
	include ('/home/steelmin/public_html/newAPIs/common/Dao.php');
	include ('/home/steelmin/public_html/newAPIs/model/class.notification.php');
	$notificationDao = new Notification();
	$notificationDao->getNotificationPreference($member_id='', $device_token=$id);//$id =>gcm_id
	
	include ('/home/steelmin/public_html/inc/desconfig.php');
	die;
}

if (isset($_REQUEST['pymtSrc']) && $_REQUEST['pymtSrc'] != ''){
	include ('/home/steelmin/public_html/inc/config1.php');
	require_once("/home/steelmin/public_html/mf.php");
	include_once ("/home/steelmin/public_html/hf.php");
	include_once ("/home/steelmin/public_html/steeladmin/hf_360.php");
	
	$order_id 			 	= $_REQUEST['order_id']; //if user is logged in then send memid / token.
	$name 			 		= $_REQUEST['name']; //if user is logged in then send memid / token.
	$phoneno 			 	= $_REQUEST['phoneno']; //if user is logged in then send memid / token.
	$company 			 	= $_REQUEST['company']; //if user is logged in then send memid / token.
	$token 			 		= $_REQUEST['token']; //if user is logged in then send memid / token.
	$email 			 		= $_REQUEST['email']; //if user is NOT logged in 
	$pymtSrc	 			= $_REQUEST['pymtSrc'];
	$amtPaidByUser	 		= $_REQUEST['price'];
	$order_status	 		= $_REQUEST['status']; //success / fail
	$payment_detail   		= $_REQUEST['payment_detail']; //whatever details related to payment can be received from the transaction; like name, email, company, card details, txn no, etc
	
	$fields_string = '';
	foreach($_REQUEST as $key=>$value) { 
		$fields_string .= $key.'='.$value. PHP_EOL; 
	}
	
	//do DB related operations ANDS send email to steelmint about the payment
	if ($token != ''){
		//get user id, email for the token
		/* $memid = qryToCommaSepString ( "
							SELECT id
							FROM `tbl_state`
							WHERE lower(`state_name`) = '$location'
						"); */
	}
	
	$html.='<table style="width:30%;border-collapse: collapse;table-layout:fixed;font-family:arial">
   <tbody>
<tr>
    <td style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Order Id<br></td>
    <td  style="word-wrap:break-word;font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$order_id.'<br></td>
</tr>
<tr>
    <td style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Name<br></td>
    <td  style="word-wrap:break-word;font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$name.'<br></td>
</tr>
<tr>
    <td width="68" style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Phone No<br></td>
    <td  style="word-wrap:break-word;color: rgb(51,51,51);font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$phoneno.'<br></td>
</tr>
<tr>
    <td style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Company<br></td>
    <td  style="word-wrap:break-word;font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$company.'<br></td>
</tr>
<tr>
    <td style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Token<br></td>
    <td  style="word-wrap:break-word;font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$token.'<br></td>
</tr>
<tr>
    <td style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Email<br></td>
    <td  style="word-wrap:break-word;font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$email.'<br></td>
</tr>
<tr>
    <td style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Payment Source<br></td>
    <td  style="word-wrap:break-word;font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$pymtSrc.'<br></td>
</tr>
<tr>
    <td style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Amount Paid<br></td>
    <td  style="word-wrap:break-word;color: rgb(51,51,51);font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$amtPaidByUser.'<br></td>
</tr>
<tr>
    <td style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Order Status<br></td>
    <td  style="word-wrap:break-word;font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$order_status.'<br></td>
</tr>
<tr>
    <td style="word-wrap:break-word;color: rgb(255,255,255);font-size: 9.0pt;font-weight: 700;text-align: left; padding-left:10px;vertical-align: middle;border-width: 0.5pt;border-style: solid;border-color: rgb(0,0,0);background: rgb(79,129,189);min-height: 14.25pt;">Payment Details<br></td>
    <td  style="word-wrap:break-word;font-size: 9.0pt;text-align: left; padding-left:10px;vertical-align: bottom;border-width: 0.5pt;border-style: solid;border-color: rgb(79,129,189);min-height: 14.25pt;">'.$payment_detail.'<br></td>
</tr>';
       
      $html.='</tbody>
        </table>';
	mailsThruMailgun($html, $email="info@steelmint.com,tarun@steelmint.com", $name_to_email_cc="", $subject="SteelMint: ($order_status) Payment received from " . $_REQUEST['pymtSrc'], "", $from_email="info@steelmint.com", $from_name="SteelMint", $reply_to="info@steelmint.com");
	include ('/home/steelmin/public_html/inc/desconfig.php');
	die;
}

include ('/home/steelmin/public_html/inc/config1.php');
require_once("/home/steelmin/public_html/mf.php");
include_once ("/home/steelmin/public_html/hf.php");
include_once ("/home/steelmin/public_html/steeladmin/hf_360.php");

//error_reporting(-1);

//// step 1 : Process Personal Details
// form deatils keep in array $arr['tbl_members'] = array(key=>valse);

/**
 * Function to generate activation link
 */
function _generateActivationMail($user_id , $user_email)
{
    $mail_activation_token = str_random($_ENV['MAIL_TOKEN_LENGTH']) ;
    $result = DB::table($_ENV['MAIL_ACTIVATION_TABLE'])->insert([ $_ENV['MAIL_ACTIVATION_USERID_COLUMN'] => $user_id,
        $_ENV['MAIL_ACTIVATION_TOKEN_COLUMN'] => $mail_activation_token ]);

    if ( $result)
    {
        $activation_link = $_ENV['EMAIL_CONFIRMATION_LINK'].'/'.$mail_activation_token ;

        $message_con = "Welcome to steelmint. To complete your registration please click the following link: ".$activation_link;

        return array(
            "email" => $user_email ,
            "from"  => $_ENV['MAIL_FROM'],
            "subject" => 'Steelmint activation' ,
            "message" => $message_con
        );
    }

}

////step 1(a) if Verification needed
function fnProcessOnVerificationOfOTP($source='', $src_from='', $require_srvc='', $memid='', $f_product='W', $price=0, $verified=0, $ip){

    if($verified==1 && $memid>0){
        mysql_query("
			update 	tbl_members
			set 	verified = 1
			where 	id = $memid")or abort(502, "Verification needed");

        ///process Payment /details
        $r1 = processServiceDetailsBeforePymt($source, $src_from, $require_srvc, $memid, $f_product, $price, $ip);
//        echo "<pre>";print_r($r);
    }
}

////step 1
function processPersonalDetails($source='website', $src_from='ONLINE', $require_srvc = 'Free Trial', $email='', $arr=array(),$f_product='W',$price=0, $ip, $from_reg = false){

    $memid = '' ;
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    require_once("/home/steelmin/public_html/mf.php");
    include_once ("/home/steelmin/public_html/hf.php");
    $chk=isEmailExists($userid='', $email, $memid, $verified);// refrence variable $memid='', $verified=0

    $_result= array();
    if($chk==1){//// Email Exists in DB
        //$src_from=$source;
        /*
        Commenting since currently not need of OTP verification at mobile level 

        if($verified==0){/// for now on hold
            //sendVerifymail($email, $arr['tbl_members']['name'], $memid);
            if($source!='mobileapp')
                sendVerifymail($email, $arr['tbl_members']['name'], $memid);
            else
                $_result = array("message" => "OTP Validation Required", "phoneno" => sendOTPOn($memid), "memid" => $memid);///return reg mobile no
        }
        */
        if($verified==0)
        {
//            $memid = mysql_query("
//			select id from tbl_members
//			where 	email = $email") or abort(502, "Verification needed");

//            $memid = mysql_query("
//			select id from tbl_members
//			where 	email = $email") ;
//
//            $memid = mysql_fetch_row($memid);

            $memid = DB::table('tbl_members')
                ->select('id')
                ->where('email' , $email)
                ->first()['id'] ;

            $arr['tbl_members']['name'];

            $user_id = $memid ;

//            $temp = _generateActivationMail($memid , $email) ;

            sendVerifymailAPI ($email, $arr['tbl_members']['name'], $memid);
//            sendSMMail($temp["message"], $email, $to_name="", $temp["subject"] );
            return ("Email Verification needed") ;
        }



        ////make entry in comments table
        $comments='';
        foreach($arr['tbl_members'] as $key=>$subvalue)
        {
            $comments = $comments." $key => ".$subvalue." <br /> ";
        }
        $arr=array();

        $arr['tbl_comments']=array(
            'f_date'=>$GLOBALS['currDate'],
            'f_time'=>$GLOBALS['currTime'],
            'comments'=>$comments,
            'memid'=>$memid,
            'comments_for'=>'W',
            'created_by'=>$src_from .' - '. $source,
        );

//        echo "tbl_create_logs";
        $res_arr=create_logs_from_array_of_array($arr);
        if ($from_reg == true )
            return ("Email Already exists") ;

    }else
    {//// Email Not Exists in DB
        //create memid ($memid)
        //$src_from='ONLINE';
        $relMngr='';
        if(isset($arr['tbl_members']['city'])){
            $relMngr=GetFirstRM($arr['tbl_members']['city'],$arr['tbl_members']['state'],$arr['tbl_members']['country']);
            ;
            $arr['tbl_members']['relMngr'] = $relMngr;
            $subRelMngr = "";
            if( "Rohan" == $relMngr)
                $subRelMngr = "Arnab";
            $arr['tbl_members']['subRelMngr'] = $subRelMngr;
        }
        $res_arr=create_logs_from_array_of_array($arr);
        //print_r($res_arr);

        // COmment not having feature currently 
        // if($source=='mobileapp')
        //     $arr['tbl_members']['verified']=1;///automatically be verified user for mobileapp

        $memid=$res_arr['tbl_members'];/// after creation return memid

        // if($source!='mobileapp')
        sendVerifymailAPI ($email, $arr['tbl_members']['name'], $memid);
//        $temp = _generateActivationMail($memid , $email) ;
//        sendSMMail($temp["message"], $email, $to_name="", $temp["subject"] );
        /* else
            sendOTPOn($memid, $arr['tbl_members']['phoneno']);///return reg mobile no */
    }

    // if(count($_result) >0 )
    //     return $_result;////OTP Validation req
    // else
    $r = processServiceDetailsBeforePymt($source, $src_from, $require_srvc, $memid, $f_product, $price, $ip);

    return $r ;

    $plan='';
    /*if($source=='mobileapp'){
        if( 'Free Trial' == $require_srvc) //if trying for free trial
        {
            return processServiceDetailsBeforePymt($source, $src_from, $require_srvc, $memid);
        }else{
            $start_date= $GLOBALS['currDate'];
            $end_date=date("Y-m-d",strtotime("$start_date +365 days"));
            $price = 0;
            $arr['tbl_reg_logs']=array(
                'memid'=>$memid,
                'startdate'=>$start_date,
                'enddate'=>$end_date,
                'f_time'=>$GLOBALS['currTime'],
                'f_product'=>'W',
                'f_tenure'=>$require_srvc,
                'status'=>'Incomplete',
                'selected_products'=>$require_srvc,
                'comments'=>$src_from  .' - '. $source,
                //'amtPaid'=>$price,
                'created_on'=>$GLOBALS['currDateTime']
            );
            $r = create_logs_from_array_of_array($arr);
            $_log_id = $r['tbl_reg_logs'];

            ///$plan = getSubscriptionPlan($source, $memid, $email);
        }
    }else{
        $start_date= $GLOBALS['currDate'];
            $end_date=date("Y-m-d",strtotime("$start_date +365 days"));
            $price = 0;
            $arr['tbl_reg_logs']=array(
                'memid'=>$memid,
                'startdate'=>$start_date,
                'enddate'=>$end_date,
                'f_time'=>$GLOBALS['currTime'],
                'f_product'=>'W',
                'f_tenure'=>$require_srvc,
                'status'=>'Incomplete',
                'selected_products'=>$require_srvc,
                'comments'=>$src_from  .' - '. $source,
                //'amtPaid'=>$price,
                'created_on'=>$GLOBALS['currDateTime']
            );
            $r = create_logs_from_array_of_array($arr);
            $_log_id = $r['tbl_reg_logs'];

            ///$plan = getSubscriptionPlan($source, $memid, $email);
    }
    */
    /* $_result = array();
    //$_result['log_id'] =  $_log_id;
    $_result['memid'] =  $memid;
    $_result['packages'] =  $plan;
    $_result['require_srvc'] =  $require_srvc;

    return $_result; */
    //return $memid.'/*/'.$_log_id.'/*/'.$plan;


}
/*
$src_from='online';
$source='mobileapp';
$require_srvc='VAS-P';
$memid=56013;
$f_product='W';
$price=2800;
$r1 = processServiceDetailsBeforePymt($source, $src_from, $require_srvc, $memid, $f_product, $price);
echo "<pre>";print_r($r1); */
/*Array
(
    [message] => You Successfully Registered
    [log_id] => 143869
    [order_id] => SM1-
    [memid] => 56013
    [amtToPay] => 2800
    [pymtURLToredirectTo] => https://www.steelmint.com/paypal/payment.php
)*/
//// step 2 : Process Service Details Before Payment
function processServiceDetailsBeforePymt($source='steelmint', $src_from='online', $require_srvc = 'Free Trial', $memid=0, $f_product='W', $price=0, $ip='')
{
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    $user_service=chkWebSrvcLogStatus($memid);

    $reg_email = qryToCommaSepString("
			select
				CASE
				WHEN send_email_to = 'R' THEN email
				ELSE addtnl_email
			   END as reg_email
			FROM tbl_members
			where id = $memid
		");

    $srvc_type = $user_service['srvc_type'];///have selected products
    $srvc_tenure = $user_service['srvc_tenure'];
    $srvc_inv_no = $user_service['inv_no'];
    $srvc_price = $user_service['srvc_price'];

    $srvc_status=$user_service['srvc_status'];
    //$srvc_price=$user_service['srvc_price'];

    $sdate=$user_service['sdate'];
    $edate=$user_service['edate'];


    if( '' != $srvc_inv_no )
        $paid_free = 'paid';
    else
        $paid_free = 'not-paid';

    if('Free Trial' == $srvc_tenure)
        $existing_srvc = 'Free Trial';
    else
    {
        if(strpos($srvc_type, 'VAS-P') !== false ){
            $existing_srvc = 'VAS-P';
            $vasp_type=allowAccessToDownloaddataInEXCEL($reg_email);
            if( $vasp_type )
                $existing_srvc = 'VAS-P+XLS';
        }
        elseif(strpos($srvc_type, 'VAS-G') !== false)
            $existing_srvc = 'VAS-G';
        elseif(strpos(strtoupper($srvc_type), 'MOBILEAPP') !== false)
            $existing_srvc = 'MOBILEAPP';
        else
            $existing_srvc='';

    }


    ////$ip =  $_SERVER['REMOTE_ADDR'] ;
    $ip_countryName ='';
    if($ip)
        $ip_countryName = ipTocntry($ip);

    /* if($ip_countryName=='INDIA')
        $_tax = $GLOBALS['taxRate'];
    else */
        $_tax = 1;

    if( 'Free Trial' == $require_srvc) //if trying for free trial
    {
        $sel_prod = 'Coal,FerroAlloy,FinishFlat,FinishLong,IronOre,Scrap,SemiFinished';

        $status_in = "'Active','Expired'";///default
        $status ="Pending";///default

        if($source=='mobileapp'){
            $status_in = "'Active'";
            $sel_prod ="MOBILEAPP";
            $status ="Active";
        }
        ///chk any records is -> active for mobile and both Active and Expired for others
        $val  = qryToCommaSepString("
				SELECT f_tenure
				from tbl_reg_logs
				where memid = $memid
				AND (( status = 'Active') or ( status = 'Expired' AND f_tenure <> 'Free Trial'))
				AND f_product = 'W'

			");//AND status in ($status_in) AND f_tenure = 'Free Trial'
        if( '' != $val || 'Active' == $srvc_status  )	{
            return "You can't take Free Trial again.";
        }else{

            $start_date= $GLOBALS['currDate'];
            $end_date=date("Y-m-d",strtotime("$start_date +14 days"));
            $arr['tbl_reg_logs']=array(
                'memid'=>$memid,
                'startdate'=>$start_date,
                'enddate'=>$end_date,
                'f_time'=>$GLOBALS['currTime'],
                'f_product'=>'W',
                'f_tenure'=>'Free Trial',
                'status'=>$status,
                'selected_products'=>$sel_prod,
                'comments'=>$src_from  .' - '. $source,
                'created_on'=>$GLOBALS['currDateTime']
            );


            $r = create_logs_from_array_of_array($arr);

            afterServiceLogCreation($memid, $reg_log_id = '-1', $pymtStatus = 'success');

            return "You Successfully Registered";
        }
    }

    if ($require_srvc != 'Free Trial')  //trying for paid
    {
        //if no W log active OR free trial + active log
        if( "Active" != $srvc_status || ("Active" == $srvc_status && 'Free Trial' == $srvc_tenure) )
        {
            $start_date= $GLOBALS['currDate'];
            $end_date=date("Y-m-d",strtotime("$start_date +365 days"));
            $price = $price * $_tax;

        }else{

            if($paid_free == 'paid' && "Active" == $srvc_status && $source=='mobileapp') {///for mobileapp
                return "error! already paid member.";
            }
            elseif($paid_free == 'paid' && ($require_srvc == $existing_srvc)) {
                $start_date=date("Y-m-d",strtotime("$edate +1 day"));/// $edate = ACTIVE LOG
                $end_date=date("Y-m-d",strtotime("$start_date +365 days"));
                $price = $price * $_tax;
            }else{
                $start_date=$GLOBALS['currDate'];
                $end_date=date("Y-m-d",strtotime("$start_date +365 days"));
                $price = $price;
                getPricesForUpgradeUser($price, $srvc_price, $start_date, $end_date, $existing_srvc, $require_srvc);
            }
        }

        $arr['tbl_reg_logs']=array(
            'memid'=>$memid,
            'startdate'=>$start_date,
            'enddate'=>$end_date,
            'f_time'=>$GLOBALS['currTime'],
            'f_product'=>'W',
            'f_tenure'=>'One Year',
            'status'=>'Pending',
            'selected_products'=>$require_srvc,///not free trial, means MOBILEAPP/VAS-P/VAS-G
            'comments'=>$src_from  .' - '. $source,
            'amtPaid'=>$price,
            'created_on'=>$GLOBALS['currDateTime']
        );
        $r = create_logs_from_array_of_array($arr);
        $_log_id = $r['tbl_reg_logs'];
        ///print_r($arr);
        $_result = array();
        $order_id = getSMorderNoForCCAVENUE("SM");

        $_result['message'] =  "You Successfully Registered";
        $_result['log_id'] =  $_log_id;
        $_result['order_id'] =  $order_id;
        $_result['memid'] =  $memid;
        $_result['amtToPay'] = $amtToPay =  $price;
        $_result['item_desc'] = "SteelMint App Payment";
        //$_result['currency'] = $currency;
        $pymtURLToredirectTo = $_result['pymtURLToredirectTo'] =  "https://www.steelmint.com/pay/newCheckOut.php";
        $_result['payment_gateway'] = "ccavenue";
        include_once("/home/steelmin/public_html/sm_group_events/regProcess/paypal_country.php");

        if( "INDIA" != strtoupper($ip_countryName)){
            if(in_array(strtoupper($ip_countryName), $_paypal_country))
                $pymtURLToredirectTo = $_result['pymtURLToredirectTo'] =  "https://www.steelmint.com/paypal/payment.php";
            else
                $pymtURLToredirectTo = $_result['pymtURLToredirectTo'] =  "https://www.steelmint.com/paypal/payment.php";

            $_result['pymtURLToredirectTo'] = $pymtURLToredirectTo;

            $_result['payment_gateway'] = "paypal";
        }

        //"$order_id."/*/".$_log_id."/*/".$memid."/*/".$amtToPay."/*/".$pymtURLToredirectTo;

        return $_result;
    }
}



/* $memid=$r1['memid'];
$reg_log_id=$r1['143869'];
//$price=2800;
$payment_details_arr=$arr;///responce from payment page
$order_status='success';
$mode='online';
$gatewayUsedToMakePymt='';//CCAVENUE, IN-APP, PAYPAL
$amtPaidByUser='';

$r2 = processDetailsAfterPymt($memid, $reg_log_id, $payment_details_arr, $order_status, $mode);
echo "<pre>";print_r($r2); */
//// step 3 : Process Details After Payment
function processDetailsAfterPymt($memid=0, $reg_log_id=0, $payment_details_arr=array(), $order_status='success', $mode='online', $gatewayUsedToMakePymt='', $amtPaidByUser=0)
{
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    $order_status = strtolower($order_status);
    if($order_status==="success")
    {
        $actual_amtPaid  = qryToCommaSepString("
				SELECT amtPaid
				from tbl_reg_logs
				where id = $reg_log_id
			");
        //return "You have not paid correct amount. Please start again.";
        if($actual_amtPaid==$amtPaidByUser)
            return array("message" => "You have not paid correct amount. Please start again.", "custom_message" => 'wrong payment amount');

        $stats = afterServiceLogCreation($memid,$reg_log_id=$payment_details_arr['merchant_param1'], $order_status, $mode, $gatewayUsedToMakePymt);

        if($payment_details_arr['merchant_param4']=='mobileapp'){	//$arr['merchant_param4']=mobileapp
            if($stats!='')
                return  array("message" => "Payment done Succesfully", "custom_message" => $stats);
            else
                return array("message" => "Successfully taken the Free Trial Serives.", "custom_message" => $stats);
        }
        elseif($payment_details_arr['merchant_param4']=='website'){	//$arr['merchant_param4']=mobileapp

            return  array("message" => "Payment done Succesfully", "custom_message" => 'https://www.steelmint.com/successfullpayment_offer.php?name='.$payment_details_arr['billing_name'].'&plan='.$payment_details_arr['merchant_param5']);
            //return $redirecturl  ='https://www.steelmint.com/successfullpayment_offer.php?name='.$payment_details_arr['billing_name'].'&plan='.$payment_details_arr['merchant_param5'];
        }else{
            return  array("message" => "Payment done Succesfully", "custom_message" => $stats);
        }

    }else{
        $stats  = afterServiceLogCreation($memid, $reg_log_id=$payment_details_arr['merchant_param1'], $order_status, $mode, $gatewayUsedToMakePymt);

        if($payment_details_arr['merchant_param4']=='mobileapp'){	//$arr['merchant_param4']=mobileapp
            //return "Payment failure";
            return  array("message" => "Payment failure", "custom_message" => $stats);
        }
        elseif($payment_details_arr['merchant_param4']=='website'){	//$arr['merchant_param4']=mobileapp
            $redirecturl  ='https://www.steelmint.com/successfullpayment_offer.php?name='.$payment_details_arr['billing_name'].'&plan='.$payment_details_arr['merchant_param5'];
            return  array("message" => "Payment failure", "custom_message" => $redirecturl);
        }else{
            return  array("message" => "Payment failure", "custom_message" => $stats);
        }
    }
    return $stats;

}

function afterServiceLogCreation($memid=0, $reg_log_id='-1', $pymtStatus = 'success', $arr=array(), $mode='Online', $gatewayUsedToMakePymt=''){


    //$memid=$arr['merchant_param2'];
    //$email=$arr['billing_email'];
    if( "-1" == $reg_log_id ){///free trail case
        /*$res1=mysql_query("select id, email, verified, name from tbl_members where id='$memid'");
        if(mysql_num_rows($res1)>0)
        {
            $r = mysql_fetch_array($res1);
            $memid	= $r['id'];
            $name	= $r['name'];
            $email	= $r['email'];
            $verified = $r['verified'];
        }

        if($verified == 0)
            sendVerifymailAPI ($email, $name, $memid);*/
        updateTbltbl_updated_reg_logs($memid);

        return '';
        ///need to ask "service started" email
        ///else
        //send "service started" email
    }

    if($pymtStatus==="Aborted" || ($pymtStatus!=="Failure" && $pymtStatus!=="success")){

        return "<br>Thank you for registring with us.We will keep you posted regarding the status of your order through e-mail";
    }elseif($memid){

        $bank_name=$payment_details_arr['bank_name'];
        list($merchant_param5, $merchant_param6, $promopage) = explode(',', $arr['merchant_param5']);

        if( strpos(strtoupper($arr['order_id']), "EVENTS") !== false  ){

            if($pymtStatus==="Failure"){
                $stats = "Unsuccessful Payment for<br /> <b> Order No: </b>" . $arr['order_id'] . " <br /> <b> Amount: </b>" . $arr['amount'] . " <br /><br>We will contact you soon.";
            }else{
                $final_inv_no = getnewInvNo('T', 'Events');

                $sqlupdate = "update tbl_sm_events_payment_details set pay_amt='". $arr['amount'] ."',pymt_details	='CCAVENUE', pym_Mode='NEFT/Online', status='Active', pay_date ='". $GLOBALS['currDateTime'] ."',paymentstatus='Paid',bank_name='".$bank_name."',comments='online Payment on ".$GLOBALS['currDateTime']." : ".$gatewayUsedToMakePymt."', inv_no='$final_inv_no' where id =" . $reg_log_id;
                $reglog_update = mysql_query($sqlupdate) or die(mysql_error() . $sqlupdate);


                $fetch_user_data =mysql_fetch_array(mysql_query("select first_name,mobile,email from tbl_sm_events_users where id = ".$memid), MYSQL_ASSOC);

                $log_id  = qryToCommaSepString("
					SELECT log_id
					from tbl_sm_events_payment_details
					where id = $reg_log_id
				");

                onSuccessfulTranscation("Offline", $Order_Id='', $inv_no, $fetch_user_data['first_name'], $fetch_user_data['email'], $memid,  $fetch_user_data['mobile'], $log_id, 'NEFT/Online', 'CCAVENUE',  trim($arr['currency']), trim($GLOBALS['currDateTime']), trim($bank_name));

                $stats = "Successful Payment for<br /> <b> Order No: </b>" . $arr['order_id'] . " <br /> <b> Amount: </b>" . $arr['amount'] . " <br /><br>We will contact you soon.";
            }
        }
        else
        {///for SteelMint

            if( "-1" != $reg_log_id ){	///paid user

                //$r_srvc_prodList = get_Srvc_prodList_for_updation_in_tbl_templates_2($memid, $email);
                //$arr_srvc_prodList = explode("/*/", $r_srvc_prodList);
                //$service_type = $arr_srvc_prodList[0];
                //$temp_details = $list = $arr_srvc_prodList[1]
                //sub_unsub_email_prefrence($memid, $subscription='subscribe', $service_type, '', $temp_details);
                $taxAmt = getTaxBreakUps($payment_details_arr['amount'], strtolower($mode));
                list($amountWOTax, $ST, $EC, $SHSC) = explode("/*/", $taxAmt);

                ///inactivate all active log
                mysql_query("
						update 	tbl_reg_logs
						set 	status = 'Inactive'
						where 	f_product = 'W'
						AND 	status = 'Active'
						AND 	id <> " .$payment_details_arr['merchant_param1'] . "
						AND		memid = ".$payment_details_arr['merchant_param2']);
                $qry="
					update 	tbl_reg_logs
					set 	pymDtls='CCAVENUE',
							pymtMode='NEFT/Online',
							billNo='".$payment_details_arr['order_id']."',
							amtPaid='".$payment_details_arr['amount']."',
							status='Active',
							datepay='".$GLOBALS['currTime']."',
							paymentstatus='Paid',
							nb_order_no='".$payment_details_arr['tracking_id']."',
							nb_bid='".$payment_details_arr['bank_ref_no']."',
							card_category='".$payment_details_arr['card_name']."',
							bank_name='".$payment_details_arr['bank_name']."',
							comments='".$payment_details_arr['failure_message'].",".$payment_details_arr['status_code'].",
							".$payment_details_arr['currency']." : ".$gatewayUsedToMakePymt."',
							acc_ver_pending = 1 ,
							ST = '$ST',
							EC = '$EC',
							SHSC = '$SHSC',
							amountWOTax = '$amountWOTax'
					where id =".$payment_details_arr['merchant_param1'];

                $reglog_update = mysql_query($qry) or die(mysql_error());


                sub_unsub_email_prefrence($memid, 'subscribe',$merchant_param5);

                if($arr['merchant_param3'] == 0)
                    sendVerifymailAPI ($arr['billing_email'], $arr['billing_name'], $arr['merchant_param1']);

                updateTbltbl_updated_reg_logs($memid);

                if($merchant_param6){/// if SMS Service Includes
                    mysql_query("
					UPDATE tbl_members
					SET `pckg_incl` = '". $merchant_param6 ."' ,
						email_category = ''
					WHERE `id` =". $memid .";
					")or die(mysql_error());
                }

                if( $pymtStatus == 'success' ){//create, send invoice as an attachment to paid client, accounts
                    $invArrDtls['memid']				=	$arr['merchant_param2'];
                    $invArrDtls['type_of_invoice']	=	"T";
                    $invArrDtls['buy_order_ref']		=	"Online";
                    $invArrDtls['srvc_type']			=	"Web";
                    $invArrDtls['web_rate']			=	$arr['amount'];
                    $invArrDtls['pymtDtls']			=	'CCAVENUE';
                    $invArrDtls['pymtDate']			=	$GLOBALS['currDate'];
                    $invArrDtls['pymtMode']			=	'NEFT/Online';
                    $invArrDtls['SMBank']				=	$bank_name;
                    $invArrDtls['currency']			=	$arr['currency'];
                    $invArrDtls['reg_log_ids']		=	$arr['merchant_param1'];
                    $encodedArr = json_encode($invArrDtls,true);
                    //generate, email invoice to client + update tbl_invoice_log table
                    inv_related($memid, "", "", 'Y', 'CCAVENUE', $arr['currency'], $encodedArr);
                    //invoice generated manullay

                    $stats = "Successful Payment <br /> <b> Order No: </b>" . $arr['order_id'] . " <br /> <b> Amount: </b>" . $arr['amount'] . " <br /> <b> Product Purchased: </b>" . $arrProd[$arr['merchant_param5']];
                }
                else
                    if($pymtStatus==="Failure"){/// payment Fail

                        $stats = "Unsuccessful Payment <br /> <b> Order No: </b>" . $arr['order_id'] . " <br /> <b> Amount: </b>" . $arr['amount'] . " <br /> <b> Product to Purchase: </b>" . $arrProd[$arr['merchant_param5']];

                        if( "" != $arr['merchant_param1'] )
                        {
                            $qry="update tbl_reg_logs set  pymDtls	='CCAVENUE', pymtMode='NEFT/Online', billNo='".$arr['order_id']."', amtPaid='0',  status='Pending', datepay='0000-00-00', nb_order_no='".$arr['tracking_id']."', nb_bid='".$arr['bank_ref_no']."', card_category='".$arr['card_name']."', bank_name='$bank_name',comments='".$arr['failure_message'].", ".$arr['status_code'].", ".$arr['currency'].": ".$gatewayUsedToMakePymt."' where id ='".$arr['merchant_param1']."'";
                            $reglog_update = mysql_query($qry) or die(mysql_error());
                        }
                        $emailTemplate = getEmailTemplate(48);
                        $sub_txt = $emailTemplate[1]['sub_txt'];
                        $msgs = str_replace("member_name", $arr['billing_name'], $emailTemplate[1]['body_txt']);

                        //email to client that his pymt was unsuccesful
                        sendSMMail($msgs, $arr['billing_email'], "", $sub_txt, "", "info@steelmint.com", "SteelMint", "info@steelmint.com");
                    }

            }
            else{
                //update email preference
                //update updated_reg_log
                //sub_unsub_email_prefrence($memid, 'subscribe', 'Free Trial');
                updateTbltbl_updated_reg_logs($memid);

            }
        }
        ////send mail to info
        $workingKey='EB10CB77A3282E019FA0291D10E74A11';		//Working Key should be provided here.
        $encResponse=$_POST["encResp"];			//This is the response sent by the CCAvenue Server
        $rcvdString=decrypt($encResponse,$workingKey);		//Crypto Decryption used as per the specified working key.
        $order_status="";
        $decryptValues=explode('&', $rcvdString);
        $dataSize=sizeof($decryptValues);
        $arr=array();

        $tbl = "<table border=\"5\" cellpadding=\"10\">";
        foreach($decryptValues as $val){
            $information=explode('=',$val);
            $tbl .=  "<tr>";
            $arr[$information[0]]=$information[1];
            $tbl .=  "<td><strong>" . $information[0] . "</strong></td>"; ;
            $tbl .=  "<td>" . $information[1] . "</td>"; ;
            $tbl .=  "</tr>";
        }
        $tbl .= "</table>";

        $msgsadmin ='
				<table width="600" border="0" cellspacing="0" cellpadding="0" >
					<tr>
						<td><img src="https://www.steelmint.com/images/logo.gif"></td>
						<td width="293">&nbsp;</td>
					</tr>
					<tr>
						<td colspan="2" align="left"><p><br />Hi,<br><br><b>'.$arr['billing_name'].'</b> has been registered for '.$arr['merchant_param5'].' with <b>'.$stats.'.</b> </p> <p> Your Service details are as follows: <br></p>
						</td>
					</tr>
					<tr>
						<td colspan="2" align="center">
							<table width="400" align="left">
								<tr>
									<td width=207><strong>Membership Id</strong></td>
									<td>'.$arr['merchant_param2'].'</td>
								</tr>
								'.$tbl.'
							</table>
						</td>
					</tr>
				</table>
			';
        //email to info@steelmint.com
        sendSMMail($msgsadmin, "info@steelmint.com", "", "Registration from ".$arr['merchant_param4'], "", "info@steelmint.com", "SteelMint", "info@steelmint.com");
    }else{
        //make entry in tbl_comments
        mysql_query("
				insert into tbl_comments
				values(	'', ".$arr['merchant_param2'].", '" . $GLOBALS['currDate'] . "', '" . $GLOBALS['currTime'] . "', 'Payment successful from ".$arr['merchant_param4']."', 'SYSTEM', 'W')
			");

        return "Invalid user id";
    }
    return $stats;
}

function getSubscriptionPlan($source='website', $memid=0 , $email='' , $ip = ''){

    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    $user_service=chkWebSrvcLogStatus($memid);

    $srvc_type = $user_service['srvc_type'];
    $srvc_tenure = $user_service['srvc_tenure'];
    $srvc_inv_no = $user_service['inv_no'];
    $srvc_price = $user_service['srvc_price'];

    if( '' != $srvc_inv_no )
        $paid_free = 'paid';
    else
        $paid_free = 'not-paid';

    $existing_srvc='';
    if('Free Trial' == $srvc_tenure)
        $existing_srvc = 'Free Trial';
    elseif ('MOBILEAPP' == $srvc_tenure)
        $existing_srvc = 'MOBILEAPP' ;
    else
    {
        if(strpos($srvc_type, 'VAS-P') !== false )
            $existing_srvc = 'VAS-P';
        if(strpos($srvc_type, 'VAS-G') !== false)
            $existing_srvc = 'VAS-G';
        $vasp_type=allowAccessToDownloaddataInEXCEL($email);
        if( $vasp_type )
            $existing_srvc = 'VAS-P+XLS';
    }

    $res_arr=array();

    $ip_countryName ='';
    if($ip)
        $ip_countryName = ipTocntry($ip);

    $currency = null ;
    $price = array() ;
if($memid==56350)
	$ip_countryName='mohanr';
    if(strtoupper($ip_countryName)=='INDIA')
    {
        $currency = "INR" ;
        $price['MOBILEAPP'] =  "12075" ;
    }

    else
    {
        $currency = "USD" ;
        $price['MOBILEAPP'] =  "190" ;
    }


    if($source=='website'){
        return $existing_srvc;
    }else{

        $res_arr['plan']["MOBILEAPP"] = array(
            'title'=>'1 Year Subscription Plan',
            "plancode" => "MOBILEAPP" ,
            'description'=>'To access full content details of News, Prices, Tenders, PlantBee and Events.',
            'price'=>$price["MOBILEAPP"],
            "currency"=> $currency ,
        );

       /*  $res_arr['plan']["Free Trial"] = array(
            'title'=>'Mobile Application (Introductory Offer- 1 Year)',
            "plancode" => "Free Trial" ,
            'description'=>'Prices, News, Tender, Logistics, Email Alert, Reports. Free Add-on	of 6 months SMS alerts worth INR 3,000/-',
            'price' => "0" ,
            "currency"=> $currency ,
            ) ; */

//        if($existing_srvc!='VAS-P+XLS' && $existing_srvc != 'VAS-P'){
//
//            $res_arr['plan'][] = array(
//                'title'=>'Standard Plan',
//                "plancode" => "VAS-P+XLS" ,
//                'description'=> 'Access to Basic Services (News, Prices, Market Trade, Comments, Graphs)<br/>Value Added Services in Application and Website',
//                'price'=>'28950',
//                'you_get'=>'you_get desc',
//                "btn" => "Buy"
//            );
//        }
//
//        if($existing_srvc!='VAS-P+XLS' && $existing_srvc != 'VAS-G'){
//            $res_arr['plan'][] = array(
//                'title'=>'Professional Plan',
//                "plancode" => "VAS-G" ,
//                'description'=>'Access to Basic Services (News, Prices, Market Trade, Comments, Graphs)<br/>No Access to Vale Added Service in Website.',
//                'price'=>'23950',
//                'you_get'=>'you_get desc2',
//                "btn" => "Buy"
//            );
//        }

       /*  if($existing_srvc == 'VAS-P+XLS' || $existing_srvc == 'VAS-P'){

            $res_arr['plan'][] = array(
                'title'=>'Standard Plan',
                "plancode" => "VAS-P+XLS" ,
                'description'=> 'Access to Basic Services (News, Prices, Market Trade, Comments, Graphs)<br/>Value Added Services in Application and Website',
            );
        }

        if($existing_srvc =='VAS-P+XLS' || $existing_srvc == 'VAS-G'){
            $res_arr['plan'][] = array(
                'title'=>'Professional Plan',
                "plancode" => "VAS-G" ,
                'description'=>'Access to Basic Services (News, Prices, Market Trade, Comments, Graphs)<br/>No Access to Vale Added Service in Website.',
            );
        } */

        $res_arr['existing_plan'] = $existing_srvc ;

        $res_arr['note'] = '* Price excluding service tax @ 14% and Swachh Bharat Cess 0.5%.
Above mentioned packages are for One Email Id and one Mobile Number only. For multiple subscription (Corporate Package) speak to our <a href="#">marketing team</a><br/>
Sharing user account details, reports or other information with other unsolicited parties is strictly prohibited. Read our <a href="#">Subscription Policy</a>';

        $res_arr['Service'] = 'Products Covered: Iron Ore Lumps & Fines, Pellets, Coal, Ferrous Scrap, Pig Iron, Sponge Iron, MS Billet, MS Ingot, TMT, Structure, Wires, Flat Steel and Ferro Alloys
<br/>
1. Basic Services: Market Trade Prices, Latest Industry News + Archive News, Expert Interviews and Comments. News Alerts - Latest News Alerts, Stock Updates, Evening Market at a Glance Mailer, Important Circulars, etc.
<br/>
2. Value Added Services: Logistics, Import-Export Data, Tenders, Archive Data Graph and Previous Prices, Live Market Tracker. ';
    }

    return $res_arr;
}

function sendOTPOn($memid=0, $phoneno=''){

    if($phoneno!='')
        return $phoneno;

    $reg_phoneno = qryToCommaSepString("
			select
				CASE
				   WHEN send_sms_to = 'R' THEN phoneno
				   ELSE alternate_mob_no
				END as phoneno
			FROM tbl_members
			where id = $memid
		");
    return $reg_phoneno;
}
include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php');

?>