<?php

	function getBetween($content,$start,$end){
	    $r = explode($start, $content);
	    if (isset($r[1])){
	        $r = explode($end, $r[1]);
	        return $r[0];
	    }
	    return '';
	}
  function splitr($str='',$bank=''){
     $result = array();
     switch($bank){
       case "HDFC":
               $content = trim(getBetween($str,"INW",".Avl bal"));
           $parts = explode(" ",$content);
               foreach($parts as $p => $v){ 
              if(strstr($v,"@")){
                 $result["conversion_rate"] = substr($v,strpos($v,"@")+1);
                 $result["currency"] = preg_replace("([0-9.]+)","",substr($v,0,strpos($v,"@")));
                 $val = substr($v,strlen($result["currency"]),strpos($v,"@"));
                 $result["deposited_amount"] = substr($val,0,strpos($val,"@"));
              } else { 
                  $result["ref_no"] = $v;
             }   
          }
          $result["deposited_in_bank_name"] = "HDFC BANK";     
       break;
       case "AXIS" :
                $content = trim(getBetween($str,"BRN-REF NO.",". Call"));
                $parts = explode(" ",$content);
               foreach($parts as $p => $v){ 
                if(strstr($v,"/")){
                   $amount_1=trim(getBetween($str,'credited with Rs.','on'));
                   $result["deposited_amount"] = substr($v,0,strpos($v,"/"));
                   $result["conversion_rate"] = round($amount_1/$result["deposited_amount"],2);
                } else if($p == 1) { 
                   $result["currency"] = $v;
                } else {  
                 $result["ref_no"] = $v;
                }
              }
          $result["deposited_in_bank_name"] = "AXIS BANK";      
       break;
      
      } 
       $result["pymt_mode"] = "SWIFT TRSFR";
       return $result;
 }

/* if (isset($_REQUEST['postCall']) && $_REQUEST['postCall'] == 'Y'){
	include ('/home/steelmin/public_html/inc/config1.php');
	echo "callDetails:" . $callDetails 				= htmlentities( json_encode(trim($_REQUEST['callDetails'])), ENT_QUOTES ) .  ' -- ' . $_REQUEST['FCM_TOKEN']; //content of the  SMS
	mysql_query("insert into  tbl_try (f_data, f_gateway_name)
			values ('$callDetails', NOW())") or die (mysql_error()); 
	echo "success";			
	include ('/home/steelmin/public_html/inc/desconfig.php');
} */	

if (isset($_REQUEST['getSMSFromAPP']) && $_REQUEST['getSMSFromAPP'] != ''){
 	/* include ('/home/steelmin/public_html/inc/config1.php');
	mysql_query("insert into tbl_try(f_data) values('" . htmlentities($_REQUEST['smsDtls'], ENT_QUOTES) . "')");
	include ('/home/steelmin/public_html/inc/desconfig.php');
	die;  */




	
	include ('/home/steelmin/public_html/inc/config1.php');
	{
	 
	  $value['smsSenderName'] = 	$_REQUEST['sendername'];	
	  $value['smsMatter'] = 	$_REQUEST['smsDtls'];	
		
      $sms_details=htmlspecialchars(mysql_real_escape_string($value['smsMatter']),ENT_QUOTES);
      //$sel_sms_det=mysql_query("SELECT id FROM tbl_bank_stmt WHERE smsDtls LIKE "%'.$sms_details.'%" ");
      $sel_sms_det=mysql_query("SELECT id FROM tbl_bank_stmt WHERE `smsDtls` LIKE '%$sms_details%' ");
      if(mysql_num_rows($sel_sms_det)>0){
        echo "SMS already exists";
        include ('/home/steelmin/public_html/inc/desconfig.php');
        die;
      }

      $dt=explode('.',$_REQUEST['timestamp']);
      $tt= str_replace("/","-",$dt[0]);
      $amount="";
      $mode="";
      $ref_no='';
      $paymode="";
      $pymt_dtls='';
      $bank_name='';
      $conversion_rate='';
      $currency='INR';
      //condition added to skip entries of return amounts in account date - 2-apil-2022
    if(!(stripos($value['smsMatter'],'NEFT RETURN-ACCOUNT DOES NOT EXIST-'))){
      if(strpos(strtoupper($value['smsSenderName']), 'HDFC') !== false){
            if(strpos(strtoupper($value['smsMatter']),'XX9922') !== false)
                $bank_name="HDFC Bank 0152 256 0009922";
            elseif(strpos(strtoupper($value['smsMatter']),'XX3540') !== false)  $bank_name="HDFC Bank 50200044893540";
      }  else if(strpos(strtoupper($value['smsSenderName']), 'AXIS') !== false)
            $bank_name="AXIS BANK RAIPUR- 913020027601670";
        else if(strpos(strtoupper($value['smsSenderName']), 'IDBI') !== false)
            $bank_name="IDBI BANK A/C.NO.0049102000048888";
}
      if ($bank_name!='') {

    if(strpos(strtoupper($value['smsSenderName']), 'HDFC') !== false && !(strpos($value['smsMatter'],'debited'))){
       //if(strpos(strtoupper($value['smsMatter']),'XX9922') && !(strpos($value['smsMatter'],'debited'))){

            //$bank_name="HDFC Bank 0152 256 0009922";

            //$amount=getBetween($value['smsMatter'],'INR','deposited');
            if(strpos($value['smsMatter'],'deposited')){
              $amount=getBetween($value['smsMatter'],'INR','deposited');
            }
            else if(strpos($value['smsMatter'],'credited')){
              $amount=getBetween($value['smsMatter'],'credited with INR ',' on ');
            }
            if(strpos($value['smsMatter'],'INW') && strpos($value['smsMatter'],'@')){

                $get_swift=splitr($value['smsMatter'],'HDFC');
                $amount=$get_swift['deposited_amount'];
                $ref_no=$get_swift['ref_no'];
                $pymt_dtls_1=getBetween($value['smsMatter'],'for','.Avl');
                $pymt_dtls=trim($pymt_dtls_1);
                $currency=$get_swift['currency'];
                $conversion_rate=$get_swift['conversion_rate'];
                $paymode=$get_swift['pymt_mode'];
            }
            else if(strpos($value['smsMatter'],'IMPS')){ 
                    $paymode='IMPS';
                    $ref_1=explode('IMPS',$value['smsMatter']);

                    $ref_2=explode('-',$ref_1['1']);
                    $ref_no=$ref_2['1'];
                    $pymt_dtls=$ref_2['2'];

                    if($pymt_dtls==''){
                       $pymt_dtls_1=getBetween($value['smsMatter'],'(',')');
                       $pymt_dtls=trim($pymt_dtls_1);

                       $ref_no=getBetween($value['smsMatter'],'Ref No. ',')');
                    }
            }
            else if(strpos(strtoupper($value['smsMatter']),'CHQ')){

                    if(strpos(strtoupper($value['smsMatter']),"UPDATE:")!== false || strpos(strtoupper($value['smsMatter']),"UPDATE!")!== false){
                      $pymt_dtls_1=getBetween($value['smsMatter'],'CHQ DEP','.Avl');
                    }
                    else{
                      $pymt_dtls_1=getBetween($value['smsMatter'],'CHQ DEP','Val');
                    }
                    $pymt_dtls=trim($pymt_dtls_1);
                    $pymt_dtls=trim($pymt_dtls,'-');
                    $ref_no='';
                    $paymode='CHEQUE';
            }
            else if(strpos($value['smsMatter'],'NEFT')){ 

                    $paymode='NEFT';
                    $ref_no_1=getBetween(strtoupper($value['smsMatter']),'STEEL MINT INFO SERVICES LLP','.AVL');
                    if($ref_no_1=='')
                      $ref_no_1=getBetween(strtoupper($value['smsMatter']),'STEELMINT INFO SERVICES LLP','.AVL');
                    if($ref_no_1=='')
                      $ref_no_1=getBetween(strtoupper($value['smsMatter']),'STEEL MINT INFO SERVICE LLP','.AVL');
                    if($ref_no_1=='')
                      $ref_no_1=getBetween(strtoupper($value['smsMatter']),'STEELMINT INFO SERVICE LLP','.AVL');
                    if($ref_no_1=='')
                      $ref_no_1=getBetween(strtoupper($value['smsMatter']),'STEELMINT INFO SERVICES LTD','.AVL');

                    $ref_no=trim($ref_no_1,'-');

                    $ref_1=explode('NEFT',$value['smsMatter']);
                  
                    $ref_2=explode('-',$ref_1['1']);

                    $count=count($ref_2);
                    $pymt_dtls_1='';
                    for($i=2;$i<$count-2;$i++){

                      $pymt_dtls_1.=$ref_2[$i]." ";

                    }
                    $pymt_dtls=trim($pymt_dtls_1);

                    if($pymt_dtls==''){
                      $__pymt_dtls=getBetween(strtoupper($value['smsMatter']),'FOR','.AVL');

                      $pymt_dtls=trim($__pymt_dtls);
                    }
                    
                }
            else if(strpos($value['smsMatter'],'RTGS')){ 
                    $paymode='RTGS';

                    $ref_1=explode('RTGS',$value['smsMatter']);

                    $ref_2=explode('-',$ref_1['1']);
                    $ref_3=explode('.',$ref_2['4']);
                    $ref_4=explode(' ',$ref_3['0']);
                    
                    $ref_no=$ref_4["0"];
                    $pymt_dtls=$ref_2['2']; 
                
                }
            else if(strpos($value['smsMatter'],'FT-') || strpos($value['smsMatter'],'FT -')){
                    $paymode='FT';
                    $value['smsMatter']= str_replace("FT -","FT-",$value['smsMatter']);

                    if(strpos(strtoupper($value['smsMatter']),"UPDATE:")!== false || strpos(strtoupper($value['smsMatter']),"UPDATE!")!== false){
                      $pymt_dtls_1=getBetween(strtoupper($value['smsMatter']),'FT','.AVL');
                    }
                    else{
                      $pymt_dtls_1=getBetween($value['smsMatter'],'FT','Val'); 
                    }

                    $pymt_dtls_2=explode('-',$pymt_dtls_1);
                    $count=count($pymt_dtls_2);
                    $pymt_dtls=$pymt_dtls_2[$count-1];
                    $ref_no=$pymt_dtls_2[$count-2];
            }
             else if(strpos($value['smsMatter'],'CASH') || strpos($value['smsMatter'],'Cash')){ 
                    $paymode='CASH';
                     //echo "Paymode: ".$paymode."<br>";
                    if(strpos(strtoupper($value['smsMatter']),"UPDATE:")!== false || strpos(strtoupper($value['smsMatter']),"UPDATE!")!== false){
                      $pymt_dtls_1=getBetween($value['smsMatter'],'CASH DEP','.Avl');
                    }
                    else{
                      $pymt_dtls_1=getBetween($value['smsMatter'],'CASH DEP','Val');
                    }

                    if($pymt_dtls_1==''){
                      $num= strripos($value['smsMatter'],"at");
                      $redfined_text= substr($value['smsMatter'],$num);
                      $pymt_dtls_1=getBetween($redfined_text,'at ','via Cash');
                    }

                    $pymt_dtls=trim($pymt_dtls_1);
                    $pymt_dtls=trim($pymt_dtls,'-');
                    $ref_no='';
            }
            else{
                    $paymode='ONLINE';
                 
                    if(strpos($value['smsMatter'],'deposited')){
                        $pymt_dtls=getBetween($value['smsMatter'],'for','.Avl');
                    }
                }
        }
        else if($bank_name=='IDBI BANK A/C.NO.0049102000048888'){

        if(strpos($value['smsMatter'],'NN48888') && !(strpos($value['smsMatter'],'debited'))){
          
          $amount_1=getBetween($value['smsMatter'],'credited Rs','Det:');
          $amount=trim($amount_1);

          if($amount==''){
            $amount_1=getBetween($value['smsMatter'],'credited by Rs','for');
            $amount=trim($amount_1);
          }

          if($amount==''){
            $amount_1=getBetween($value['smsMatter'],'credited for Rs','through');
            $amount=trim($amount_1); 
          }

          if(strpos($value['smsMatter'],'NEFT')){ 

                 $paymode='NEFT';

                 $ref_no=getBetween($value['smsMatter'],'NEFT-','. A/c');
                 $pymt_dtls_1=getBetween($value['smsMatter'],'Det:','. A/c');
                 $pymt_dtls=trim($pymt_dtls_1);
                    
            }
            else if(strpos($value['smsMatter'],'RTGS')){ 

                 $paymode='RTGS';

                 $ref_no=getBetween($value['smsMatter'],'RTGS/','. A/c');
                 $pymt_dtls_1=getBetween($value['smsMatter'],'Det:','. A/c');
                 $pymt_dtls=trim($pymt_dtls_1);
                    
            }
            else{

                $paymode='ONLINE';

                 $ref_no=getBetween($value['smsMatter'],'Det: ','. A/c');
                 $pymt_dtls_1=getBetween($value['smsMatter'],'Det: ','. A/c');
                 $pymt_dtls=trim($pymt_dtls_1);

                 if($pymt_dtls==''){
                  $pymt_dtls_1=getBetween($value['smsMatter'],'through','. A/c');
                  $pymt_dtls=trim($pymt_dtls_1);
                 }
            }
           }
        }
    else if($bank_name=='AXIS BANK RAIPUR- 913020027601670'){

      if(strpos($value['smsMatter'],'601670') && !(strpos($value['smsMatter'],'debited'))){

            if(strpos($value['smsMatter'],'NEFT')){ 

                 $amount_1=getBetween($value['smsMatter'],'credited with Rs.','on');
                 $amount=trim($amount_1);
               
                 $paymode='NEFT';
                 $pymt_dtls_1=getBetween($value['smsMatter'],'Info: NEFT/','.');
                 $pymt_dtls_2=explode('/',$pymt_dtls_1);
                 $ref_no=trim($pymt_dtls_2['0']);
                 $pymt_dtls=trim($pymt_dtls_2['1']);                    
              }
             else if(strpos($value['smsMatter'],'Cheque')){
                 $paymode='CHEQUE';

                 $amount_1=getBetween($value['smsMatter'],'for Rs. ','is deposited');
                 $amount=trim($amount_1);
                 $ref_no='';
                 $pymt_dtls=''; 
              }
            else if(strpos($value['smsMatter'],'BRN-REF NO.')){
                $get_swift=splitr($value['smsMatter'],'AXIS');
                $amount=$get_swift['deposited_amount'];
                $ref_no=$get_swift['ref_no'];
                $pymt_dtls_1=getBetween($value['smsMatter'],'Info:','. ');
                $pymt_dtls=trim($pymt_dtls_1);
                $currency=$get_swift['currency'];
                $conversion_rate=$get_swift['conversion_rate'];
                $paymode=$get_swift['pymt_mode'];
            }
            else{
                $amount_1=getBetween($value['smsMatter'],'credited with Rs.','on');
                $amount=trim($amount_1);

                if($amount==''){
                  $amount_1=getBetween($value['smsMatter'],'Credited Rs','on');
                  $amount=trim($amount_1);
                }

                $paymode='ONLINE';
                $pymt_dtls_1=getBetween($value['smsMatter'],'Info: ','.');
                $pymt_dtls_2=explode('/',$pymt_dtls_1);
                $ref_no=trim($pymt_dtls_2['1']);
                $pymt_dtls=trim($pymt_dtls_2['0']);
            }
          }
   
        }
        if($amount!='' && !empty($amount)){
         // echo "<pre>";
          if(strpos($value['smsMatter'],'PAYPAL PAYMENTS PL') || (strpos($value['smsMatter'],'M/S AVENUES (INDIA)')) || (strpos($value['smsMatter'],'M/S AVENUES (INDIA)')) || (strpos($value['smsMatter'],'AVENUES INDIA PVT LTD')) || (strpos($value['smsMatter'],'WORKING ACCOUNT')) || (strpos($value['smsMatter'],'HDFC MUTUAL FUND')) || (strpos($value['smsMatter'],'HDFC BALANCED ADVAN')) ){

            $show_in_listing='N';
          }
          else{
            $show_in_listing='Y';
          }
          mysql_query ("INSERT INTO tbl_bank_stmt SET 
                          f_datetime=CURTIME(), 
                          ref_no='".$ref_no."', 
                          deposited_amount='".trim(str_replace(",","",$amount))."', 
                          pymt_mode='".$paymode."', 
                          deposited_datetime='".date('Y-m-d H:i:s',strtotime($tt))."',
                          
                          currency='".$currency."',
                          conversion_rate='".$conversion_rate."',
                          sender_name='".htmlspecialchars(mysql_real_escape_string($value['smsSenderName']),ENT_QUOTES)."', 
                          smsDtls='".htmlspecialchars(mysql_real_escape_string($value['smsMatter']),ENT_QUOTES)."', 
                          pymt_dtls='".htmlspecialchars(mysql_real_escape_string($pymt_dtls),ENT_QUOTES)."',
                          show_in_listing='".$show_in_listing."',
                          deposited_in_bank_name='".htmlspecialchars(mysql_real_escape_string($bank_name),ENT_QUOTES)."'")
           or die(mysql_error());
         //echo "</pre>";
           $insert_id=mysql_insert_id();
           echo $insert_id;
       }
       else{
          echo "not inserted - Amount is Blank / Format Not Considered / Debited Case / SenderName Not considered";
      }
       }
  }

	// mysql_query("insert into  tbl_bank_stmt (f_datetime, smsDtls)
	// 		values (NOW(), '$smsDtls')") or die (mysql_error()); 
	//echo "success";		
	include ('/home/steelmin/public_html/inc/desconfig.php');
}	
	
if (isset($_REQUEST['getSMSFromAPP1']) && $_REQUEST['getSMSFromAPP1'] != ''){
	include ('/home/steelmin/public_html/inc/config1.php');
	/* $smsMatter 				= trim($_REQUEST['smsMatter']); //content of the  SMS
	$smsSenderName 			= trim($_REQUEST['smsSenderName']); //sender name / number of the  SMS
	$smsDateTime 			= trim($_REQUEST['smsDateTime']); //sent datetime of the  SMS
	
	//don't insert duplicate SMSes based on $smsDateTime
	//extract deposited_in_bank_name, amount, ref_no,  pymt_mode from $smsMatter
	mysql_query("insert into  tbl_bank_stmt (f_datetime, pymt_dtls, sender_name, deposited_datetime)
			values (NOW(), '$smsMatter', '$smsSenderName', '$smsDateTime')") or die (mysql_error()); */
	//$smsDtls 				= htmlentities( json_encode(trim($_REQUEST['smsDtls'])), ENT_QUOTES ); //content of the  SMS



	//echo "hi sm"; die;
	//echo "<br />smsDtls:" . $smsDtls=trim($_REQUEST['smsDtls']) . "<br />";

	$smsArr=json_decode(trim($_REQUEST['smsDtls']),1);

	foreach ($smsArr as $key => $value) {
   
      $dt=explode('.',$value['smsDateTime']);
      $tt= str_replace("/","-",$dt[0]);
      $amount="";
      $mode="";
      $ref_no='';
      $paymode="";
      $pymt_dtls='';
      $bank_name='';
      $conversion_rate='';
      $currency='INR';

      if(strpos(strtoupper($value['smsSenderName']), 'HDFC') !== false)
            $bank_name="HDFC Bank 0152 256 0009922";
        else if(strpos(strtoupper($value['smsSenderName']), 'AXIS') !== false)
            $bank_name="AXIS BANK RAIPUR- 913020027601670";
        else if(strpos(strtoupper($value['smsSenderName']), 'IDBI') !== false)
            $bank_name="IDBI BANK A/C.NO.0049102000048888";

      if ($bank_name!='') {

       if(strpos($value['smsMatter'],'XX9922') && !(strpos($value['smsMatter'],'debited'))){

        $bank_name="HDFC Bank 0152 256 0009922";

            //$amount=getBetween($value['smsMatter'],'INR','deposited');
            if(strpos($value['smsMatter'],'deposited')){
              $amount=getBetween($value['smsMatter'],'INR','deposited');
            }
            else if(strpos($value['smsMatter'],'credited')){
              $amount=getBetween($value['smsMatter'],'credited with INR ',' on ');
            }
            if(strpos($value['smsMatter'],'INW') && strpos($value['smsMatter'],'@')){

                $get_swift=splitr($value['smsMatter'],'HDFC');
                $amount=$get_swift['deposited_amount'];
                $ref_no=$get_swift['ref_no'];
                $pymt_dtls_1=getBetween($value['smsMatter'],'for','.Avl');
                $pymt_dtls=trim($pymt_dtls_1);
                $currency=$get_swift['currency'];
                $conversion_rate=$get_swift['conversion_rate'];
                $paymode=$get_swift['pymt_mode'];
            }
            else if(strpos($value['smsMatter'],'IMPS')){ 
                    $paymode='IMPS';
                    $ref_1=explode('IMPS',$value['smsMatter']);

                    $ref_2=explode('-',$ref_1['1']);
                    $ref_no=$ref_2['1'];
                    $pymt_dtls=$ref_2['2'];
            }
            else if(strpos(strtoupper($value['smsMatter']),'CHQ')){

                    if(strpos(($value['smsMatter']),"UPDATE:")!== false){
                      $pymt_dtls_1=getBetween($value['smsMatter'],'CHQ DEP','.Avl');
                    }
                    else{
                      $pymt_dtls_1=getBetween($value['smsMatter'],'CHQ DEP','Val');
                    }
                    $pymt_dtls=trim($pymt_dtls_1);
                    $pymt_dtls=trim($pymt_dtls,'-');
                    $ref_no='';
                    $paymode='CHEQUE';
            }
            else if(strpos($value['smsMatter'],'NEFT')){ 

                    $paymode='NEFT';
                    $ref_no_1=getBetween(strtoupper($value['smsMatter']),'STEEL MINT INFO SERVICES LLP','.AVL');
                    if($ref_no_1=='')
                      $ref_no_1=getBetween(strtoupper($value['smsMatter']),'STEELMINT INFO SERVICES LLP','.AVL');
                    if($ref_no_1=='')
                      $ref_no_1=getBetween(strtoupper($value['smsMatter']),'STEEL MINT INFO SERVICE LLP','.AVL');
                    if($ref_no_1=='')
                      $ref_no_1=getBetween(strtoupper($value['smsMatter']),'STEELMINT INFO SERVICE LLP','.AVL');

                    $ref_no=trim($ref_no_1,'-');

                    $ref_1=explode('NEFT',$value['smsMatter']);
                  
                    $ref_2=explode('-',$ref_1['1']);

                    $count=count($ref_2);
                    $pymt_dtls_1='';
                    for($i=2;$i<$count-2;$i++){

                      $pymt_dtls_1.=$ref_2[$i]." ";

                    }
                    $pymt_dtls=trim($pymt_dtls_1);
                    
                }
            else if(strpos($value['smsMatter'],'RTGS')){ 
                    $paymode='RTGS';

                    $ref_1=explode('RTGS',$value['smsMatter']);

                    $ref_2=explode('-',$ref_1['1']);
                    $ref_3=explode('.',$ref_2['4']);
                    $ref_4=explode(' ',$ref_3['0']);
                    
                    $ref_no=$ref_4["0"];
                    $pymt_dtls=$ref_2['2']; 
                
                }
            else if(strpos($value['smsMatter'],'FT-') || strpos($value['smsMatter'],'FT -')){
                    $paymode='FT';
                    $value['smsMatter']= str_replace("FT -","FT-",$value['smsMatter']);

                    if(strpos(($value['smsMatter']),"UPDATE:")!== false){
                      $pymt_dtls_1=getBetween(strtoupper($value['smsMatter']),'FT','.AVL');
                    }
                    else{
                      $pymt_dtls_1=getBetween($value['smsMatter'],'FT','Val'); 
                    }

                    $pymt_dtls_2=explode('-',$pymt_dtls_1);
                    $count=count($pymt_dtls_2);
                    $pymt_dtls=$pymt_dtls_2[$count-1];
                    $ref_no=$pymt_dtls_2[$count-2];
            }
             else if(strpos($value['smsMatter'],'CASH')){ 
                    $paymode='CASH';
                     //echo "Paymode: ".$paymode."<br>";
                    if(strpos(($value['smsMatter']),"UPDATE:")!== false){
                      $pymt_dtls_1=getBetween($value['smsMatter'],'CASH DEP','.Avl');
                    }
                    else{
                      $pymt_dtls_1=getBetween($value['smsMatter'],'CASH DEP','Val');
                    }
                    $pymt_dtls=trim($pymt_dtls_1);
                    $pymt_dtls=trim($pymt_dtls,'-');
                    $ref_no='';
            }
            else{
                    $paymode='ONLINE';
                 
                    if(strpos($value['smsMatter'],'deposited')){
                        $pymt_dtls=getBetween($value['smsMatter'],'for','.Avl');
                    }
                }
        }
        else if($bank_name=='IDBI BANK A/C.NO.0049102000048888'){

        if(strpos($value['smsMatter'],'NN48888') && !(strpos($value['smsMatter'],'debited'))){
          
          $amount_1=getBetween($value['smsMatter'],'credited Rs','Det:');
          $amount=trim($amount_1);

          if($amount==''){
            $amount_1=getBetween($value['smsMatter'],'credited by Rs','for');
            $amount=trim($amount_1);
          }

          if(strpos($value['smsMatter'],'NEFT')){ 

                 $paymode='NEFT';

                 $ref_no=getBetween($value['smsMatter'],'NEFT-','. A/c');
                 $pymt_dtls_1=getBetween($value['smsMatter'],'Det:','. A/c');
                 $pymt_dtls=trim($pymt_dtls_1);
                    
            }
            else if(strpos($value['smsMatter'],'RTGS')){ 

                 $paymode='RTGS';

                 $ref_no=getBetween($value['smsMatter'],'RTGS/','. A/c');
                 $pymt_dtls_1=getBetween($value['smsMatter'],'Det:','. A/c');
                 $pymt_dtls=trim($pymt_dtls_1);
                    
            }
            else{

                $paymode='ONLINE';

                 $ref_no=getBetween($value['smsMatter'],'Det: ','. A/c');
                 $pymt_dtls_1=getBetween($value['smsMatter'],'Det: ','. A/c');
                 $pymt_dtls=trim($pymt_dtls_1);
            }
           }
        }
    else if($bank_name=='AXIS BANK RAIPUR- 913020027601670'){

      if(strpos($value['smsMatter'],'601670') && !(strpos($value['smsMatter'],'debited'))){

            if(strpos($value['smsMatter'],'NEFT')){ 

                 $amount_1=getBetween($value['smsMatter'],'credited with Rs.','on');
                 $amount=trim($amount_1);
               
                 $paymode='NEFT';
                 $pymt_dtls_1=getBetween($value['smsMatter'],'Info: NEFT/','.');
                 $pymt_dtls_2=explode('/',$pymt_dtls_1);
                 $ref_no=trim($pymt_dtls_2['0']);
                 $pymt_dtls=trim($pymt_dtls_2['1']);                    
              }
             else if(strpos($value['smsMatter'],'Cheque')){
                 $paymode='CHEQUE';

                 $amount_1=getBetween($value['smsMatter'],'for Rs. ','is deposited');
                 $amount=trim($amount_1);
                 $ref_no='';
                 $pymt_dtls=''; 
              }
            else if(strpos($value['smsMatter'],'BRN-REF NO.')){
                $get_swift=splitr($value['smsMatter'],'AXIS');
                $amount=$get_swift['deposited_amount'];
                $ref_no=$get_swift['ref_no'];
                $pymt_dtls_1=getBetween($value['smsMatter'],'Info:','. ');
                $pymt_dtls=trim($pymt_dtls_1);
                $currency=$get_swift['currency'];
                $conversion_rate=$get_swift['conversion_rate'];
                $paymode=$get_swift['pymt_mode'];
            }
            else{
                $amount_1=getBetween($value['smsMatter'],'credited with Rs.','on');
                $amount=trim($amount_1);

                $paymode='ONLINE';
                $pymt_dtls_1=getBetween($value['smsMatter'],'Info: ','.');
                $pymt_dtls_2=explode('/',$pymt_dtls_1);
                $ref_no=trim($pymt_dtls_2['1']);
                $pymt_dtls=trim($pymt_dtls_2['0']); 
            }
          }
   
        }
        if($amount!='' && !empty($amount)){
         // echo "<pre>";
          if(strpos($value['smsMatter'],'PAYPAL PAYMENTS PL') || (strpos($value['smsMatter'],'M/S AVENUES (INDIA)')) || (strpos($value['smsMatter'],'M/S AVENUES (INDIA)')) || (strpos($value['smsMatter'],'AVENUES INDIA PVT LTD')) || (strpos($value['smsMatter'],'WORKING ACCOUNT')) || (strpos($value['smsMatter'],'HDFC MUTUAL FUND')) || (strpos($value['smsMatter'],'HDFC BALANCED ADVAN')) ){

            $show_in_listing='N';
          }
          else{
            $show_in_listing='Y';
          }
          mysql_query ("INSERT INTO tbl_bank_stmt SET 
                          f_datetime=CURTIME(), 
                          ref_no='".$ref_no."', 
                          deposited_amount='".trim(str_replace(",","",$amount))."', 
                          pymt_mode='".$paymode."', 
                          deposited_datetime='".date('Y-m-d H:i:s',strtotime($tt))."',
                          currency='".$currency."',
                          conversion_rate='".$conversion_rate."',
                          sender_name='".htmlspecialchars(mysql_real_escape_string($value['smsSenderName']),ENT_QUOTES)."', 
                          smsDtls='".htmlspecialchars(mysql_real_escape_string($value['smsMatter']),ENT_QUOTES)."', 
                          pymt_dtls='".htmlspecialchars(mysql_real_escape_string($pymt_dtls),ENT_QUOTES)."',
                          show_in_listing='".$show_in_listing."',
                          deposited_in_bank_name='".htmlspecialchars(mysql_real_escape_string($bank_name),ENT_QUOTES)."'")
           or die(mysql_error());
         //echo "</pre>";
       }
         
      }
  }

	// mysql_query("insert into  tbl_bank_stmt (f_datetime, smsDtls)
	// 		values (NOW(), '$smsDtls')") or die (mysql_error()); 
	echo "success";		
	include ('/home/steelmin/public_html/inc/desconfig.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');
	include ('/home/steelmin/public_html/plantbee/hf.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;
				}
			}
		}
		
		$appType = 'SM';
		$f_product_in = "'MA', 'W'";
		$_email_from="info@steelmint.com";
		$_email_from_name="SteelMint";
		$service_type = 'MA';
		$company_name = 'steelmint';
		$selected_products = 'Mobile App';
		$_doman_name = 'www.steelmint.com';
		if(isset($_REQUEST['appType']) && $_REQUEST['appType']=='CM'){ 
			$appType = $_REQUEST['appType'];
			$f_product_in = "'C'";
			$_email_from = "info@coalmint.com";
			$_email_from_name = "CoalMint";
			$service_type = "C";
			$company_name = 'coalmint';
			$selected_products = 'Standard';
			$_doman_name = 'www.coalmint.com';
		}
		
    	if(isset($_REQUEST['currency']))
    		$currency = $_REQUEST['currency'];	
    	if(isset($_REQUEST['price']))
    		$price = $_REQUEST['price'];	
    	sendVerifymail_new($member_id, $_doman_name);
		$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 ( $f_product_in )
					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 http-equiv="Content-Type" content="text/html; charset=utf-8"><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"], "MOBAPP") ;
					
					sendSMMail($msgs="memid: <a href='https://www.steelmint.com/steeladmin/operations/tem_screenshot/html/index_new.php?id=$member_id'> $member_id </a> <br /> trying to re take free trial. Has been denied to him.", $b["rmEmail"] . ",".$_email_from, $name_to_email_cc="", $subject="$_email_from_name Mobile App: Client re-trying to take free trial", $attachment="", $from_email=$_email_from, $from_name=$_email_from_name, $reply_to=$_email_from);					
				} else 
					$gvFreeTrial = 1;
            } else {   	
				$gvFreeTrial = 1;
            }	  

			if($gvFreeTrial == 1){
				//$rm_arr =getRMForRoutingProcess($member_id, $company_name='steelmint', 'A1');
				$lead_type='A1';
				//if($chk==1){
					//$lead_type = getLastLeadType($member_id, $service_type='MA');
					/////$leadtypeArr = getLastLeadType($member_id, $service_type='MA',$dflag='true');
					$leadtypeArr = getLastLeadType($member_id, $service_type,$dflag='true');
					if(isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type']!='')
						$lead_type = $leadtypeArr['lead_type'];
					if(isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type']!='')
						$mood = $leadtypeArr['mood'];
					if(isset($leadtypeArr['fudate']) && $leadtypeArr['fudate']!='')
						$fudate = $leadtypeArr['fudate']; 
					
					if($lead_type=='A5' || $lead_type=='B5')
						$lead_type='A11';
				//}	
				$rm_arr =getRMForRoutingProcess($member_id, $company_name, $lead_type);
				
				//following status has been changed to Inactive on 2017-12-23 by tarun as sumit asked not to gv ne free trial to users from APP
				$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'=>$service_type,
					'f_tenure'=>'Free Trial',
					'status'=>'Inactive',
					'selected_products'=>$selected_products,
					'comments'=>"from ".$company_name." mobile app",
					'created_on'=>date("Y-m-d H:i:s"),
					'lead_type'=>$lead_type,
					'fudate'=>$fudate,
					'rm'=>$rm_arr['rm_id'],
					'subrm'=>$rm_arr['subrm_id'],
					'mood'=>$mood,
					'no_of_memids' => 1,
					'f_currency' => $currency,
					'pipeline_status'=>'New',
					'routing_status'=>$lead_type,
					'first_log_id' => $rm_arr['first_log_id']
				);	
				 $r = create_logs_from_array_of_array($arr);
				 
				$_log_id=$r['tbl_reg_logs'];
				if(!empty($_log_id) && $rm_arr['first_log_id']=='')
				{
					$_newUpdtArr['tbl_reg_logs']['first_log_id']=$_log_id;
					update_table_from_array_of_array($_newUpdtArr,$_log_id);					
				}
				
				 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 =  getSMorderNoForCCAVENUE("SM");
    	    } 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($appType=='CM'){ 
					///$appType = $_REQUEST['appType'];

					if( $currency == "USD"){
						if(in_array(strtoupper($ip_countryName), $_paypal_country)){
							//$pymtURLToredirectTo =  BASEURL."pay/commonCheckOut.php";
							$pymtURLToredirectTo =  BASEURL."paypal/common_payment.php";
							//$pymtURLToredirectTo =  BASEURL."paypal/payment.php";
							//$received_thru = "Paypal";
							$received_thru = "CCAvenue - Internationa";
							$price= 399;
						} else {
							$pymtURLToredirectTo =  BASEURL."pay/commonCheckOut.php";
							$received_thru = "CCAvenue - International";
							$price=399;
						}	
					} else {
						$received_thru = "CCAvenue - Domestic";
						$pymtURLToredirectTo = BASEURL."pay/commonCheckOut.php";
						$price=24950;
					}
				}else{///SM
				
					//added code to update currency based on location for 12+1 offer 
					if(isset($_REQUEST['frm_r_mail']) && $_REQUEST['frm_r_mail']!=''){
						$member_country = qryToCommaSepString("select country from tbl_members where id=$member_id");
						if($member_country=='113' OR empty($member_country))
							$currency = 'INR';
						else
							$currency = 'USD';    			
				    }
				    
				    
					if( $currency == "USD"){
						if(in_array(strtoupper($ip_countryName), $_paypal_country)){
							//$pymtURLToredirectTo =  BASEURL."pay/commonCheckOut.php";
							$pymtURLToredirectTo =  BASEURL."paypal/common_payment.php";
							//$pymtURLToredirectTo =  BASEURL."paypal/payment.php";
							//$received_thru = "Paypal";
							$received_thru = "CCAvenue - Internationa";
							//$price= 225;
							
						} else {
							$pymtURLToredirectTo =  BASEURL."pay/commonCheckOut.php";
							$received_thru = "CCAvenue - International";
							//$price=225;
						}
						//updated as per new website package
						
						$selected_products = '53';
						$price = qryToCommaSepString("select totalAmount_With_GST from tbl_packages where id=53");
						if($price==0 || empty($price))
							$price= 195;
					} else {
						$received_thru = "CCAvenue - Domestic";
						$pymtURLToredirectTo = BASEURL."pay/commonCheckOut.php";
						//$price=12500;
						//updated as per new website package						
						$selected_products = '49';
						$price = qryToCommaSepString("select totalAmount_With_GST from tbl_packages where id=49");
						if($price==0 || empty($price))
							$price= 14042;
					}
				}
    	    }
			$_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 ( $f_product_in )    
    			");
				if($enddate)
					$start_date=date("Y-m-d",strtotime("$enddate +1 days"));
				else
					$start_date= date("Y-m-d");
		
		$pymDtls_old='';$receipt_no_old='';
    		$end_date=date("Y-m-d",strtotime("$start_date +365 days"));
    		if(isset($_REQUEST['frm_r_mail']) && $_REQUEST['frm_r_mail']!=''){
				if($enddate!='' && $enddate){
					$end_date=date("Y-m-d",strtotime("$end_date +1 month"));
				}
				else{	
					$enddate_exp10='';
					$enddate_exp10  = qryToCommaSepString("
    				SELECT enddate
    				from tbl_reg_logs
    				where memid = $member_id
    				AND inv_no != ''
    				AND DATE_ADD(enddate, INTERVAL 10 DAY)>=CURDATE() and enddate<=CURDATE()
    				AND status not in ('','Pending')
    				AND f_product IN ( $f_product_in )    
    			");
    			 if($enddate_exp10){
					$end_date=date("Y-m-d",strtotime("$end_date +1 month"));
    			 }
				}
				
				$pymDtls_old	 ='From Renewal Mail';
				$receipt_no_old = trim($_REQUEST['c_track']);
				//$price = $_REQUEST['price'];
    		}
    		
    		
			//$rm_arr =getRMForRoutingProcess($member_id, $company_name='steelmint', 'A1');
			$lead_type='A1';
			//if($chk==1){
				//$lead_type = getLastLeadType($member_id, $service_type='MA');
				$leadtypeArr = getLastLeadType($member_id, $service_type,$dflag='true');
					if(isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type']!='')
						$lead_type = $leadtypeArr['lead_type'];
					if(isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type']!='')
						$mood = $leadtypeArr['mood'];
					if(isset($leadtypeArr['fudate']) && $leadtypeArr['fudate']!='')
						$fudate = $leadtypeArr['fudate']; 
					
				if($lead_type=='A5' || $lead_type=='B5')
					$lead_type='A11';
			//}	
			$rm_arr =getRMForRoutingProcess($member_id, $company_name, $lead_type);
			
			$arr['tbl_reg_logs']=array(
    			'memid'=>$member_id,
    			'startdate'=>$start_date,
    			'enddate'=>$end_date,
    			'f_time'=>$GLOBALS['currTime'],
    			'f_product'=>$service_type,
    			'f_tenure'=>'One Year',
    			'status'=>'Pending',
    			'selected_products'=>$selected_products,
    			'comments'=>"from ".$company_name." mobile app",
    			'amtPaid'=>$price,
    			'amountWOTax'=>$price,
    			'created_on'=>date("Y-m-d H:i:s"),
    			'received_thru' => $received_thru,
    			'billNo' => $order_id,
    			'f_currency' => $currency,
    			'no_of_memids' => 1,
				'lead_type'=>$lead_type,
				'fudate'=>$fudate,
				'rm'=>$rm_arr['rm_id'],
				'subrm'=>$rm_arr['subrm_id'],
				'mood'=>$mood,
				'pipeline_status'=>'New',
				'routing_status'=>$lead_type,
				'acc_ver_pending'=>1,
				'first_log_id' => $rm_arr['first_log_id'],
				'pymDtls_old'=> $pymDtls_old,
				'receipt_no_old'=> $receipt_no_old
			);	
			 $r = create_logs_from_array_of_array($arr);
			 
			$_log_id=$r['tbl_reg_logs'];
			if(!empty($_log_id) && $rm_arr['first_log_id']=='')
			{
				$_newUpdtArr['tbl_reg_logs']['first_log_id']=$_log_id;
				update_table_from_array_of_array($_newUpdtArr,$_log_id);					
			}
			
			updateTbltbl_updated_reg_logs($member_id);
			 
    		//$price = 1; //for testing; remove this line
    		 if($_REQUEST['plancode'] == 'ios'){
    		    $result["log_id"] = $_log_id;     
    		    echo json_encode($result); 
    		 } else {
    			if( $pymtURLToredirectTo ==  BASEURL."pay/commonCheckOut.php" )
    				header("Location:" . $pymtURLToredirectTo . "?reglogs_id=$_log_id&uid=$member_id&pymtSrc=mobileapp&productPurchased=MOB_APP&amt=$price&currency=$currency&orderid=$order_id&page_name=$appType");
    			else
    				header("Location:" . $pymtURLToredirectTo . "?reglogs_id=$_log_id&uid=".$member_id."&pymtSrc=mobileapp&productPurchased=Payment for Order :".$order_id."&amt=".$price."&output=embed&page_name=$appType&orderid=" . $order_id. "&crency=$currency&currency=$currency");
    		 }
    	} /* 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' || $_REQUEST['FCM_tag'] == 'ios')){
	include ('/home/steelmin/public_html/inc/config1.php');

	include_once ('/home/steelmin/public_html/hf.php'); 
	$token 				= trim($_REQUEST['token']); //if user is logged in then send memid / token.
	$device_id 			= trim($_REQUEST['device_id']); //if user is logged in then send memid / token.
	$device 		= trim($_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.
	$deviceInfo 		= $_REQUEST['deviceInfo']; //get user's device info like comapny, model no., OS, version, steelmint app version
	
	//"translate_to" => "Hindi,Chinese,Russian,English,Japanese"
	$res_arr = array(
				"latest_app_version_in_play_store" => "5.8.6", // used to intimate the user to install new version of APP if his existing version is less than this value
				"allow_copy_news" => 0, // used in news desciption screen;  if 1 => allow user to copy the news, else disallow him to copy the news.
				"translate_to" => array('en'=> "English",
										'hi'=> "Hindi",
										'ja'=> "Japanese",
										'zh-CN'=> "Chinese",
										'ru'=> "Russian",
									)// used in news desciption screen; sends languages in which the news needs to be translated to
			);
	//print_r($_REQUEST);		
	if($device == 'ios'){
		$res_arr = array(
				"status#" =>"1",
				"message#" => "Device already registered",
				"latest_app_version_in_play_store" => "6.8.0",
				"allow_copy_news" => "0".$device
			);
	}
	$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 json_encode($res_arr);
			include ('/home/steelmin/public_html/inc/desconfig.php');
			die;
		}
	}

	if( $device_id == '' && $device == ''){
		if($device =='ios'){
			echo 'Unauthorized action. Token access denied';
		}else{
			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 ){
		$memid_immortal = qryToCommaSepString ( "
							SELECT memid_immortal
							FROM `gcm_device`
							WHERE user_id = $user_id
							and memid_immortal=0
						");
						
		$b = mysql_fetch_array($a);
		$id = $b['id'] ;	
		$user_id_in_db = $b['user_id'] ;	
		
		$memid_immortal_col_updt='';
		if($memid_immortal=='')			
			$memid_immortal_col_updt = " ,memid_immortal=$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  */ //by tanvi 17th may
			
			//check if this user_id is updated in any other log of gcm_device or not
			// if yes => multi login case; 2 diff devices logging with same credentials;
			// logout user on existing APP, and login him to new APP
			/* $gcmTblId = qryToCommaSepString ( "
							SELECT id
							FROM `gcm_device`
							WHERE user_id = $user_id
							limit 0,1
						");
			if( $gcmTblId != '' ){
				mysql_query("update gcm_device set user_id = 0  where user_id = $user_id ");
				mysql_query("update tbl_notification_preference set f_device_token = '$gcmTblId'  where member_id = $user_id ");
				mysql_query("update tbl_notification_preference set member_id = 0  where member_id = $user_id ");
			}	 */			
			
			/*mysql_query("update gcm_device set user_id = $user_id, FCM_tag='$FCM_tag' $memid_immortal_col_updt 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; same device, same credentials; probably, uninstalled w/o logout and trying to re-login with same credentials */ //by tanvi 17th may
			/* if($memid_immortal=='')		
				mysql_query("update gcm_device set user_id = $user_id, memid_immortal=$user_id ,FCM_tag='$FCM_tag'  where id = $id  ");
			else */
				/*mysql_query("update gcm_device set user_id = $user_id,  FCM_tag='$FCM_tag' $memid_immortal_col_updt where id = $id  ");
		}
		if($device =='ios'){
			$res_arr = array(
				"status#" =>"1",
				"message#" => "Device already registered",
				"latest_app_version_in_play_store" => "6.8.0",
				"allow_copy_news" => "0"
			);
		}
	} else {
		
		if( $user_id != 0 ){ */ //by tanvi 17th may
			// someone has tried to login in another device with same user_id. 
			// 1. mark him memid = 0 in gcm_device
			// 2. mark him memid = 0, update gcm_tbl_id in tbl_notification_preference
			
			/* $gcmTblId = qryToCommaSepString ( "
							SELECT id
							FROM `gcm_device`
							WHERE user_id = $user_id
							limit 0,1
						");
			if( $gcmTblId != '' ){
				mysql_query("update gcm_device set user_id = 0  where user_id = $user_id ");
				mysql_query("update tbl_notification_preference set f_device_token = '$gcmTblId'  where member_id = $user_id ");
				mysql_query("update tbl_notification_preference set member_id = 0  where member_id = $user_id ");
			} */			
		/*}
		
		mysql_query("insert into gcm_device (device, device_id, FCM_tag, created_at, user_id, physical_id, memid_immortal)
			values ('$device', '$device_id', '$FCM_tag', '$c_at', $user_id, '$physical_id', $user_id)") or die (mysql_error());
		$id = mysql_insert_id();
		
		if($device =='ios'){
			$res_arr = array(
				 "status#" =>"1",
				"latest_app_version_in_play_store" => "6.8.0",
				"allow_copy_news" => "0"
			);
		}
	}
	if($token != '' && $user_id != 0){
		mysql_query("UPDATE gcm_device SET deviceInfo='".$deviceInfo."' WHERE user_id=".$user_id."");
	}
	elseif ($device_id != ''){
		mysql_query("UPDATE gcm_device SET deviceInfo='".$deviceInfo."' WHERE device_id='".$device_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');
	
	echo json_encode($res_arr);
	
	die;
}*/ //close

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

	include_once ('/home/steelmin/public_html/hf.php');

	$token 				= isset($_REQUEST['token']) ? trim($_REQUEST['token']):'' ; //if user is logged in then send memid / token.
	$device_id 			= isset($_REQUEST['device_id']) ? trim($_REQUEST['device_id']):'' ; //if user is logged in then send memid / token.
	$device 		= isset($_REQUEST['device']) ? trim($_REQUEST['device']):'' ; //if user is logged in then send memid / token.
	$physical_id 		= isset($_REQUEST['physical_id']) ? $_REQUEST['physical_id']:'' ; //if user is logged in then send memid / token.
	$FCM_tag 			= isset($_REQUEST['FCM_tag']) ? $_REQUEST['FCM_tag']:'' ; //if user is logged in then send memid / token.
	$deviceInfo 		= isset($_REQUEST['deviceInfo']) ? trim($_REQUEST['deviceInfo']):'' ; //get user's device info like comapny, model no., OS, version, steelmint app version
	$memid=isset($_REQUEST['member_id']) ? $_REQUEST['member_id']:0 ;

/* $pm =  $token.'->'.$device_id.'->'.  $device.'->'. $physical_id.'->'. $deviceInfo; 
mysql_query("insert into tbl_try set f_data = '$pm' "); */

	/*new code for ADmod by tanvi start*/

	$recoveredData_admob = file_get_contents('/home/steelmin/public_html/images/manage_banner/images/admob.json');
	if($recoveredData_admob!='')
		$get_data_admob = unserialize($recoveredData_admob);

	/*if(isset($get_data_admob['video']['url']))
		$video_url=$get_data_admob['video']['url'];
	else
		$video_url="";*/

	if(isset($get_data_admob['image']['image']))
		$file_path_img=BASEURL."images/manage_banner/images/admob/image/".$get_data_admob['image']['image'];
	else
		$file_path_img="";

	/*if($video_url!='')
		$type='video';
	else if($file_path_img!='')
		$type='image';*/

	/*new code for ADmod by tanvi end*/

	//echo "Token: ".$token." Device_id: ".$device_id;

$appType = 'SM';
if(isset($_REQUEST['appType']) && $_REQUEST['appType']!=''){ 
	$appType = $_REQUEST['appType'];
}

$clause_for_notf='';
$_app_ver="8.2"; 
if($appType == 'CM'){
	$_app_ver="1.2";
	
	/* if(isset($_REQUEST['news']))
			$clause_for_notf.="news=".$_REQUEST['news'].", ";
	if(isset($_REQUEST['prices']))
			$clause_for_notf.="prices=".$_REQUEST['prices'].", ";
	if(isset($_REQUEST['tenders']))
			$clause_for_notf.="tenders=".$_REQUEST['tenders'].", ";
	if(isset($_REQUEST['india']))
			$clause_for_notf.="india=".$_REQUEST['india'].", ";
	if(isset($_REQUEST['china']))
			$clause_for_notf.="china=".$_REQUEST['china'].", ";
	if(isset($_REQUEST['japan_korea']))
			$clause_for_notf.="japan_korea=".$_REQUEST['japan_korea'].", ";
	if(isset($_REQUEST['pakistan_bangladesh_nepal']))
			$clause_for_notf.="pakistan_bangladesh_nepal=".$_REQUEST['pakistan_bangladesh_nepal'].", ";	
	if(isset($_REQUEST['australia']))
			$clause_for_notf.="australia=".$_REQUEST['australia'].", ";
	if(isset($_REQUEST['south_east_asia']))
			$clause_for_notf.="south_east_asia=".$_REQUEST['south_east_asia'].", ";
	if(isset($_REQUEST['ferro_alloy']))
			$clause_for_notf.="ferro_alloy=".$_REQUEST['ferro_alloy'].", ";
	if(isset($_REQUEST['middle_east_africa']))
			$clause_for_notf.="middle_east_africa=".$_REQUEST['middle_east_africa'].", ";
	if(isset($_REQUEST['cis_nations']))
			$clause_for_notf.="cis_nations=".$_REQUEST['cis_nations'].", ";
	if(isset($_REQUEST['europe']))
			$clause_for_notf.="europe=".$_REQUEST['europe'].", ";
	if(isset($_REQUEST['us_canada']))
			$clause_for_notf.="us_canada=".$_REQUEST['us_canada'].", ";
	if(isset($_REQUEST['brazil']))
			$clause_for_notf.="brazil=".$_REQUEST['brazil'].", ";
	if(isset($_REQUEST['global']))
			$clause_for_notf.="global=".$_REQUEST['global']." "; */
}else{///for steelmint
	if(isset($_REQUEST['iron_ore']))
			$clause_for_notf.=", iron_ore=".$_REQUEST['iron_ore'].", ";
	if(isset($_REQUEST['coal']))
			$clause_for_notf.="coal=".$_REQUEST['coal'].", ";
	if(isset($_REQUEST['ferrous_scrap']))
			$clause_for_notf.="ferrous_scrap=".$_REQUEST['ferrous_scrap'].", ";				
	if(isset($_REQUEST['ship_breaking']))
			$clause_for_notf.="ship_breaking=".$_REQUEST['ship_breaking'].", ";
	if(isset($_REQUEST['semi_finish']))
			$clause_for_notf.="semi_finish=".$_REQUEST['semi_finish'].", ";
	if(isset($_REQUEST['finish_long']))
			$clause_for_notf.="finish_long=".$_REQUEST['finish_long'].", ";
	if(isset($_REQUEST['finish_flat']))
			$clause_for_notf.="finish_flat=".$_REQUEST['finish_flat'].", ";
	if(isset($_REQUEST['ferro_alloy']))
			$clause_for_notf.="ferro_alloy=".$_REQUEST['ferro_alloy'].", ";
	if(isset($_REQUEST['graphite_electrodes']))
			$clause_for_notf.="graphite_electrodes=".$_REQUEST['graphite_electrodes'].", ";
	if(isset($_REQUEST['news']))
			$clause_for_notf.="news=".$_REQUEST['news'].", ";
	if(isset($_REQUEST['prices']))
			$clause_for_notf.="prices=".$_REQUEST['prices'].", ";
	if(isset($_REQUEST['tenders']))
			$clause_for_notf.="tenders=".$_REQUEST['tenders'].", ";
	if(isset($_REQUEST['india']))
			$clause_for_notf.="india=".$_REQUEST['india'].", ";
	if(isset($_REQUEST['china']))
			$clause_for_notf.="china=".$_REQUEST['china'].", ";
	if(isset($_REQUEST['japan_korea']))
			$clause_for_notf.="japan_korea=".$_REQUEST['japan_korea'].", ";
	if(isset($_REQUEST['pakistan_bangladesh_nepal']))
			$clause_for_notf.="pakistan_bangladesh_nepal=".$_REQUEST['pakistan_bangladesh_nepal'].", ";	
	if(isset($_REQUEST['australia']))
			$clause_for_notf.="australia=".$_REQUEST['australia'].", ";
	if(isset($_REQUEST['south_east_asia']))
			$clause_for_notf.="south_east_asia=".$_REQUEST['south_east_asia'].", ";
	if(isset($_REQUEST['ferro_alloy']))
			$clause_for_notf.="ferro_alloy=".$_REQUEST['ferro_alloy'].", ";
	if(isset($_REQUEST['graphite_electrodes']))
			$clause_for_notf.="graphite_electrodes=".$_REQUEST['graphite_electrodes'].", ";
	if(isset($_REQUEST['middle_east_africa']))
			$clause_for_notf.="middle_east_africa=".$_REQUEST['middle_east_africa'].", ";
	if(isset($_REQUEST['cis_nations']))
			$clause_for_notf.="cis_nations=".$_REQUEST['cis_nations'].", ";
	if(isset($_REQUEST['europe']))
			$clause_for_notf.="europe=".$_REQUEST['europe'].", ";
	if(isset($_REQUEST['us_canada']))
			$clause_for_notf.="us_canada=".$_REQUEST['us_canada'].", ";
	if(isset($_REQUEST['brazil']))
			$clause_for_notf.="brazil=".$_REQUEST['brazil'].", ";
	if(isset($_REQUEST['global']))
			$clause_for_notf.="global=".$_REQUEST['global']." ";

}
	/* $sel_admob=mysql_query("SELECT admob FROM gcm_device WHERE device_id='".$device_id."' and appType='$appType'");
	$cnt_admob=mysql_num_rows($sel_admob);

	if($cnt_admob==0)
	{
		$show_admob='Y';
	}
	else{
		$res_admob=mysql_fetch_array($sel_admob);
		$show_admob=$res_admob['admob'];
	} */

  $show_admob='Y';
$file_path_img = "https://www.steelmint.com/fileForMail/CoalMint_Mobile_App_500x800.png";

	$res_arr = array(
				"latest_app_version_in_play_store" => $_app_ver, // used to intimate the user to install new version of APP if his existing version is less than this value
				"allow_copy_news" => 0, // used in news desciption screen;  if 1 => allow user to copy the news, else disallow him to copy the news.
				"translate_to" => array('en'=> "English",
										'hi'=> "Hindi",
										'ja'=> "Japanese",
										'zh-CN'=> "Chinese",
										'ru'=> "Russian"
									), // used in news desciption screen; sends languages in which the news needs to be translated to
				"show_admob" =>$show_admob,
				"image_url" => $file_path_img,
				"type" => 'image',
				"event_id"=>'17'
			);
	//print_r($_REQUEST);		
	if($device == 'ios'){
		$res_arr = array(
				"status#" =>"1",
				"message#" => "Device already registered",
				"latest_app_version_in_play_store" => $_app_ver,
				"allow_copy_news" => "0".$device ,
				"show_admob" =>$show_admob,
				"image_url" => $file_path_img,
				"type" => 'image',
				"event_id"=>'17'
			);
	}

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

	$user_id= 0 ;
	if( $memid != '' && $memid != 0 ){
		$user_id = $memid;
	}
	elseif( $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 json_encode($res_arr);
			include (DIR_APPLICATION . 'inc/desconfig.php');
			die;
		}
	}

	//echo "User_id: ".$user_id;
		
	if($user_id != 0){   //if memid or token is passed
		//chk if device_id and device combination exist

		$get_userid=mysql_query("SELECT user_id FROM gcm_device WHERE device='".$device."' AND device_id='".$device_id."' and appType='$appType'");
		if(mysql_num_rows($get_userid)==0){ //not exist
			mysql_query("update gcm_device set user_id = 0 WHERE user_id=$user_id, deviceInfo='".$deviceInfo."' and appType='$appType'");

			//insert data in gcm_device
			if($appType == 'CM'){
				$insert="INSERT INTO gcm_device SET 
						created_at=CURTIME(),
						device='".$device."',
						device_id='".$device_id."',
						user_id=".$user_id.",
						memid_immortal=".$user_id.",
						deviceInfo='".$deviceInfo."',
						physical_id='".$physical_id."',
						FCM_tag='".$FCM_tag."',
						status='enable',
						
						news=1,
						prices=1,
						tenders=1,
						india=1,
						china=1,
						japan_korea=1,
						pakistan_bangladesh_nepal=1,
						australia=1,
						south_east_asia=1,
						middle_east_africa=1,
						cis_nations=1,
						europe=1,
						us_canada=1,
						brazil=1,
						global=1,
						appType='CM'
				";
				
				//$query=mysql_query($insert);
			}else{
			//insert data in gcm_device
				$insert="INSERT INTO gcm_device SET 
						created_at=CURTIME(),
						device='".$device."',
						device_id='".$device_id."',
						user_id=".$user_id.",
						memid_immortal=".$user_id.",
						deviceInfo='".$deviceInfo."',
						physical_id='".$physical_id."',
						FCM_tag='".$FCM_tag."',
						status='enable',
						iron_ore=1,
						coal=1,
						ferrous_scrap=1,
						ship_breaking=1,
						semi_finish=1,
						finish_long=1,
						finish_flat=1,
						ferro_alloy=1,
						graphite_electrodes=1,
						news=1,
						prices=1,
						tenders=1,
						india=1,
						china=1,
						japan_korea=1,
						pakistan_bangladesh_nepal=1,
						australia=1,
						south_east_asia=1,
						middle_east_africa=1,
						cis_nations=1,
						europe=1,
						us_canada=1,
						brazil=1,
						global=1,
						appType='SM'
					";
			
					$query=mysql_query($insert);
			}

					/*if($query)
						return 1;*/

			if($device =='ios'){
				$res_arr = array(
					 "status#" =>"1",
					"latest_app_version_in_play_store" => $_app_ver,
					"allow_copy_news" => "0",
					"show_admob" =>$show_admob,
					"image_url" => $file_path_img,
					"type" => 'image',
					"event_id"=>'17'
				);
			}
		}
		else{
			//if device_id and device combination is present in gcm_device table
			mysql_query("update gcm_device set user_id = 0 WHERE user_id=$user_id, deviceInfo='".$deviceInfo."' and appType='$appType' ");
			//update data
			if($clause_for_notf!='')
						$user_id=0;
					
			$update="UPDATE gcm_device SET deviceInfo='".$deviceInfo."', user_id=".$user_id.", memid_immortal=".$user_id.", updated_at=CURTIME() "; 
			if($clause_for_notf!='')
				$update.=$clause_for_notf;

			$update.=" WHERE device='".$device."' AND device_id='".$device_id."' and appType='$appType'";

			$query=mysql_query($update);
			/*if($query)
				return 1;*/
			if($device =='ios'){
				$res_arr = array(
						"status#" =>"1",
						"message#" => "Device already registered",
						"latest_app_version_in_play_store" => $_app_ver,
						"allow_copy_news" => "0",
						"show_admob" =>$show_admob,
						"image_url" => $file_path_img,
						"type" => 'image',
						"event_id"=>''
					);
			}
		}
	} else { // no user_id found
		
		$get_userid=mysql_query("SELECT id FROM gcm_device WHERE device='".$device."' AND device_id='".$device_id."' and appType='$appType'");
		if(mysql_num_rows($get_userid) > 0){ //record with $device + $device_id  exists in gcm_device
			$update="UPDATE gcm_device SET user_id = 0 ";
			if($clause_for_notf!='')
				$update.=$clause_for_notf;
			$update.=" WHERE device='".$device."' AND device_id='".$device_id."' and appType='$appType'";
			$query=mysql_query($update);

			/*if($query)
				return 1;*/

			if($device =='ios'){
				$res_arr = array(
						"status#" =>"1",
						"latest_app_version_in_play_store" => $_app_ver,
						"allow_copy_news" => "0",
						"show_admob" =>$show_admob,
						"image_url" => $file_path_img,
						"type" => 'image',
						"event_id"=>''
					);
			}

		} else { //record with $device + $device_id NOT exists in gcm_device
			//insert one row in gcm_device for 		
			//insert data in gcm_device
			if($appType == 'CM'){	
				$insert="INSERT INTO gcm_device SET 
								created_at=CURTIME(),
								device='".$device."',
								device_id='".$device_id."',
								user_id=0,
								memid_immortal=0,
								deviceInfo='".$deviceInfo."',
								physical_id='".$physical_id."',
								FCM_tag='".$FCM_tag."',
								status='enable',								
								news=1,
								prices=1,
								tenders=1,
								india=1,
								china=1,
								japan_korea=1,
								pakistan_bangladesh_nepal=1,
								australia=1,
								south_east_asia=1,
								middle_east_africa=1,
								cis_nations=1,
								europe=1,
								us_canada=1,
								brazil=1,
								global=1,
								appType='CM'
					";		
					///$query=mysql_query($insert);	

					/*if($query)
						return 1;*/

			}else{	
				$insert="INSERT INTO gcm_device SET 
							created_at=CURTIME(),
							device='".$device."',
							device_id='".$device_id."',
							user_id=0,
							memid_immortal=0,
							deviceInfo='".$deviceInfo."',
							physical_id='".$physical_id."',
							FCM_tag='".$FCM_tag."',
							status='enable',
							iron_ore=1,
							coal=1,
							ferrous_scrap=1,
							ship_breaking=1,
							semi_finish=1,
							finish_long=1,
							finish_flat=1,
							ferro_alloy=1, 
							graphite_electrodes=1,
							news=1,
							prices=1,
							tenders=1,
							india=1,
							china=1,
							japan_korea=1,
							pakistan_bangladesh_nepal=1,
							australia=1,
							south_east_asia=1,
							middle_east_africa=1,
							cis_nations=1,
							europe=1,
							us_canada=1,
							brazil=1,
							global=1,
							appType='SM'
					";		
					$query=mysql_query($insert);	

					/*if($query)
						return 1;*/

			}
			//echo $insert;
			
			if($device =='ios'){
				$res_arr = array(
					 "status#" =>"1",
					"latest_app_version_in_play_store" => $_app_ver,
					"allow_copy_news" => "0",
					"show_admob" =>$show_admob,
					"image_url" => $file_path_img,
					"type" => 'image',
					"event_id"=>'17'
				);
			}
		}
	}

	include ('/home/steelmin/public_html/inc/desconfig.php');
	
	echo json_encode($res_arr);
}


if(isset($_REQUEST['image_url']) && (isset($_REQUEST['show_admob']) && $_REQUEST['show_admob']=='Y')){

	include ('/home/steelmin/public_html/inc/config1.php');

	$device_id= isset($_REQUEST['device_id']) ? trim($_REQUEST['device_id']):'' ;

	if($device_id!=''){

	$update_admob=mysql_query("UPDATE gcm_device SET admob='N' WHERE device_id='".$device_id."'");

	$insert_admob_clicks=mysql_query("INSERT INTO tbl_admob_clicks SET 
										created_at=NOW(), 
										device_id='".$device_id."', 
										url='".$_REQUEST['image_url']."'
									");
			$res_arr = array(
				"status#" =>"1",
				"message#" => "SUCCESS",
			);
	}
	else{

			$res_arr = array(
				"status#" =>"0",
				"message#" => "DEVICE ID IS BLANK",
			);
	}
	include ('/home/steelmin/public_html/inc/desconfig.php');
	echo json_encode($res_arr);
}

//$show_admob 			= isset($_REQUEST['show_admob']) ? trim($_REQUEST['show_admob']):'N' ;
	
	/*if(isset($_REQUEST['image_url']) && (isset($_REQUEST['show_admob']) && $_REQUEST['show_admob']=='Y'))
		$show_admob='N';
	else
		$show_admob='Y';*/


//Called from APP onclick of -> settings - logcat detials
//it is used to get log details of user when somehting goes wrong in his device.
if (isset($_REQUEST['logcat_details']) && $_REQUEST['logcat_details'] != ''){
	include_once '/home/steelmin/public_html/inc/config1.php';
	include_once '/home/steelmin/public_html/hf.php';
	include_once '/home/steelmin/public_html/mf.php';
	
	$email = $_REQUEST['device_token'];
	
	$appType='SteelMint';
	if(isset($_REQUEST['appType']) && strtoupper($_REQUEST['appType']) == 'CM'){   
		$appType='CoalMint';
	}
	/* $email = qryToCommaSepString("	
									SELECT CASE
															 WHEN send_email_to = 'R' THEN email
															 ELSE addtnl_email
															END as email
									FROM tbl_members 
									where id = 
									(select user_id
									from gcm_device
									where device_id = '$device_token')
								"); */
	if( isset($_REQUEST['aboutIssueDetails']) )
		$msg = "Issue Details: <br /><br />" . $_REQUEST['aboutIssueDetails'] . "<br /><br />Logcat:  <br /><br />" . base64_decode($_REQUEST['logcat_details']);
	else
		$msg = "Logcat:  <br /><br />" . base64_decode($_REQUEST['logcat_details']);
	
	mailThruMadMini_individual_emails($msg, "yashwant@steelmintgroup.com,prem@theitbooth.com,tarun@steelmint.com", "", $appType." APP - logcat details", '', $email, $appType, $email);
	$res_arr = array("status" => array(
		"code" =>"1001",
		"message#" => "Sent logcat details successfully",
	));
	echo json_encode($res_arr);	
	include_once '/home/steelmin/public_html/inc/desconfig.php';		
}	
	
if (isset($_REQUEST['FCM_tag1']) && $_REQUEST['FCM_tag1'] == 'FCM1'){
	include ('/home/steelmin/public_html/inc/config1.php');
	include_once ('/home/steelmin/public_html/hf.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.
	$deviceInfo 		= $_REQUEST['deviceInfo']; //get user's device info like comapny, model no., OS, version, steelmint app version

	$res_arr = array(
				"latest_app_version_in_play_store" => "6.8.0", // used to intimate the user to install new version of APP if his existing version is less than this value
				"allow_copy_news" => 0, // used in news desciption screen;  if 1 => allow user to copy the news, else disallow him to copy the news.
				"translate_to" => array('en'=> "English",
										'hi'=> "Hindi",
										'ja'=> "Japanese",
										'zh-CN'=> "Chinese",
										'ru'=> "Russian",
									) // used in news desciption screen; sends languages in which the news needs to be translated to
			);
	$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 json_encode($res_arr);
			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 ){
		/* $memid_immortal = qryToCommaSepString ( "
							SELECT memid_immortal
							FROM `gcm_device`
							WHERE user_id = $user_id
							and memid_immortal=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
			
			/* if($memid_immortal=='')			
				mysql_query("update gcm_device set user_id = $user_id, memid_immortal=$user_id, FCM_tag='$FCM_tag'  where id = $id  ");
			else */
			
			//check if this user_id is updated in any other log of gcm_device or not
			// if yes => multi login case; 2 diff devices logging with same credentials;
			// logout user on existing APP, and login him to new APP
			$gcmTblId = qryToCommaSepString ( "
							SELECT id
							FROM `gcm_device`
							WHERE user_id = $user_id
							limit 0,1
						");
			if( $gcmTblId != '' ){
				mysql_query("update gcm_device set user_id = 0  where user_id = $user_id ");
				mysql_query("update tbl_notification_preference set f_device_token = $gcmTblId  where member_id = $user_id ");
				mysql_query("update tbl_notification_preference set member_id = 0  where member_id = $user_id ");
			}				
			
			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; same device, same credentials; probably, uninstalled w/o logout and trying to re-login with same credentials
			/* if($memid_immortal=='')		
				mysql_query("update gcm_device set user_id = $user_id, memid_immortal=$user_id ,FCM_tag='$FCM_tag'  where id = $id  ");
			else */
				mysql_query("update gcm_device set user_id = $user_id,  FCM_tag='$FCM_tag'  where id = $id  ");
		}
	} else {
		
		if( $user_id != 0 ){ 
			// someone has tried to login in another device with same user_id. 
			// 1. mark him memid = 0 in gcm_device
			// 2. mark him memid = 0, update gcm_tbl_id in tbl_notification_preference
			
			$gcmTblId = qryToCommaSepString ( "
							SELECT id
							FROM `gcm_device`
							WHERE user_id = $user_id
							limit 0,1
						");
			if( $gcmTblId != '' ){
				mysql_query("update gcm_device set user_id = 0  where user_id = $user_id ");
				mysql_query("update tbl_notification_preference set f_device_token = $gcmTblId  where member_id = $user_id ");
				mysql_query("update tbl_notification_preference set member_id = 0  where member_id = $user_id ");
			}			
		}
		
		mysql_query("insert into gcm_device (device, device_id, FCM_tag, created_at, user_id, physical_id, memid_immortal)
			values ('$device', '$device_id', '$FCM_tag', '$c_at', $user_id, '$physical_id', $user_id)") or die (mysql_error());
		$id = mysql_insert_id();
	}
	if($token != '' && $user_id != 0){
		mysql_query("UPDATE gcm_device SET deviceInfo='".$deviceInfo."' WHERE user_id=".$user_id."");
	}
	elseif ($device_id != ''){
		mysql_query("UPDATE gcm_device SET deviceInfo='".$deviceInfo."' WHERE device_id='".$device_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');
	
	echo json_encode($res_arr);
	
	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");
	
	$log_id 			 	= $_REQUEST['log_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
	$order_id	 		= $_REQUEST['order_id']; //order_id
	$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.'<br>'; 
	}
	sendSMMail($fields_string, 'mohan@theitbooth.com,akash.dhomne@theitbooth.com', $to_name="", "SteelMint:ios payment tracking" ); */
	$adminMsg = '';
	//do DB related operations ANDS send email to steelmint about the payment
	//if ($token != '' && $order_status == 'Success'){
	$memid = qryToCommaSepString ( "
						SELECT id
						FROM `tokens`
						WHERE token = '$token'
					");
	if(isset($_REQUEST['member_id']) && $memid==''){
		$memid = $_REQUEST['member_id'];
	}
		
	if (strtolower($order_status) == 'success'){
		$adminMsg = 'done; Invoice needed to be created';
		
		//get user id, email for the token
/* 		$memid = qryToCommaSepString ( "
							SELECT id
							FROM `tokens`
							WHERE token = '$token'
						");
		if(isset($_REQUEST['member_id']) && $memid==''){
			$memid = $_REQUEST['member_id'];
		}
 */		//inactivate all active Free Trial MA logs, except the one to update pymt dtls for, of memid 
		mysql_query("
					update 	tbl_reg_logs 
					set 	status = 'Inactive',
							inactive_comments = 'inactivated from reg_process_steps.php - under pymtSrc if condition as user paid from ios app'
					where 	f_product = 'MA'
					AND		f_tenure = 'Free Trial'
					AND		status = 'Active'	
					AND		memid = ".$memid);
		/* mysql_query("
					update 	tbl_reg_logs 
					set 	status = 'Inactive',
							inactive_comments = 'inactivated from reg_process_steps.php - under pymtSrc if condition as user paid from ios app'
					where 	f_product = 'MA'
					AND		f_tenure = 'One year'
					AND		memid = ".$memid. "
					AND		status = 'Active'	
					AND		startdate <> '" . date("Y-m-d") . "'
					");	 */	
		/* $maxLogId = qryToCommaSepString ( "select max(id) from tbl_reg_logs where memid = $memid	
			and f_product = 'MA'		
			and status = 'Pending'
			and f_tenure = 'One Year'
			and startdate = '" . date("Y-m-d") . "'");	
			
		$currencyOfPymt = qryToCommaSepString ( "select f_currency from tbl_reg_logs where id = $maxLogId ");	 */
			$currencyOfPymt = qryToCommaSepString ( "select f_currency from tbl_reg_logs where id = $log_id ");
			
		$currency = '';
		if( strpos($amtPaidByUser, "USD") !== false )
			$currency = ",f_currency=USD";
		
		$amtPaidByUser	= htmlentities($amtPaidByUser, ENT_QUOTES);
		
		//value of $amtPaidByUser rcvd from app is in format like:  "â‚¹Â 12,500.00"; we hv to extract 12500 from it.
		////$exA = explode(".", $amtPaidByUser);
		////$amtPaidByUser = str_replace(",", "", $exA[0]);
		//$amtPaidByUser = preg_replace('/[^0-9]/', '', $amtPaidByUser);
		//,billNo='".$order_id."', paymentstatus='Paid'	
		mysql_query("
			update tbl_reg_logs
			set pymDtls='ios', 
				$currency
				pymtMode='in-app purchase', 
				offline_attachment = 'updated from reg_process_steps',
				
				status='Active', 
				datepay='".date("Y-m-d")."',
				paymentstatus='Paid',
				acc_ver_pending = 1 
			where id = $log_id
		");
		
		//include_once $_ENV['COMMON_ROOT_PATH']."steeladmin/invoices/invoice_function_sm.php";
		//include_once "/home/steelmin/public_html/steeladmin/invoices/invoice_function_sm.php";
		//$inv_file = generateInvoice($company='SM', $reg_logs_id=$log_id, 'online');
		
		//if($verified == 0)
		//	sendVerifymail($billing_email=$email, $billing_name=$name , $reg_logs_id=$log_id);
					
		updateTbltbl_updated_reg_logs($memid);
		
		$stats = "Successful Payment <br /> <b> Order No: </b>" . $order_id . " <br /> <b> Amount: </b>" . $Amount . " <br /> <b> Product Purchased: </b>Mobile App";
		$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>'.$billing_name.'</b> has been registered for ios app with <b>'.$stats.'.</b> </p> <p> 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>'.$memid.'</td>
								</tr> 										
							</table>
							'.$tbl.'
						</td>
					</tr> 
				</table>
			';
		$sender="SteelMint";
		$sender_email="info@steelmint.com";
		$sender_url=BASEURL."";
		$ureg_res = mysql_query("select (select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.rm) as relMngr,
					(select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.subrm) as subRelMngr from tbl_updated_reg_logs as ureg where memid=$memid and services in ('W','MA','S','E') limit 1");
		$ureg_row = mysql_fetch_array($ureg_res);
		
		if( $ureg_row['relMngr'] != '') 
			$rmEmail = $ureg_row['relMngr'];
		if(  $ureg_row['subRelMngr'] != '' ) 
			$rmEmail =$ureg_row['subRelMngr'];
		//sendSMMail($msgsadmin, 'mohan@theitbooth.com', "", "Registration from ".$pymtSrc, "", $sender_email, $sender, $sender_email);
		sendSMMail($msgsadmin, $rmEmail . ',accounts@steelmint.com,virendra@steelmint.com', "", "Registration from ".$pymtSrc, "", $sender_email, $sender, $sender_email);
	} else{//Order Status <> 'success' 
		if($log_id){
			mysql_query("
				update tbl_reg_logs
				set pymDtls='ios', 
					pymtMode='in-app purchase', 
					offline_attachment = 'updated from reg_process_steps',
					status='Pending', 
					datepay='0000-00-00', 
					paymentstatus='Failed'	
				where id = $log_id
			");
			
			//make an entry in tbl_comments	
			mysql_query("insert into tbl_comments ('f_date', 'f_time', 'comments', 'memid', 'comments_for', 'created_by')
			values ('" . date("Y-m-d") . "', '" . date("H:i:s") . "', 'iOS in-app purchase payment failed', '$memid', 'MA', 'auto after in-app pymt failure')"); 
		}
		linkSentAfterPymtFailure($email, $log_id);
	}
	$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;">'.$currencyOfPymt . ' ' . $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>
<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;">Service Activation<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;">' . $adminMsg . '<br></td>
</tr>
';
       
      $html.='</tbody>
        </table>';
	mailsThruMailgun($html, $email="tarun@steelmint.com,info@steelmint.com,accounts@steelmint.com,$RM_email", $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");
	
	
	/* if( $order_status == 'Success' )
		mailsThruMailgun($html, $email="accounts@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'=>'MA',
            '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;
	
	$field_array = array();
	$field_array =  array('camp_code'=>'CAMP19' ,'memid'=>$memid);
	addCampaignHistory($field_array);
	
	$lead_type='A1';
	//if($chk==1){
		//$lead_type = getLastLeadType($memid, $service_type='MA');
		$leadtypeArr = getLastLeadType($memid, $service_type='MA',$dflag='true');
		if(isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type']!='')
			$lead_type = $leadtypeArr['lead_type'];
		if(isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type']!='')
			$mood = $leadtypeArr['mood'];
		if(isset($leadtypeArr['fudate']) && $leadtypeArr['fudate']!='')
			$fudate = $leadtypeArr['fudate']; 
		
		if($lead_type=='A5' || $lead_type=='B5')
			$lead_type='A11';
	//}	
	$rm_arr =getRMForRoutingProcess($memid, $company_name='steelmint', $lead_type);
	
    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 in ( 'W', 'M')

			");//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'=>'MA',
                'f_tenure'=>'Free Trial',
                'status'=>$status,
                'selected_products'=>$sel_prod,
                'comments'=>$src_from  .' - '. $source,
                'created_on'=>$GLOBALS['currDateTime'],
				'lead_type'=>$lead_type,
				'fudate'=>$fudate,
				'rm'=>$rm_arr['rm_id'],
				'subrm'=>$rm_arr['subrm_id'],
				'mood'=>$mood,
				'pipeline_status'=>'New',
				'routing_status'=>$lead_type,
				'first_log_id' => $rm_arr['first_log_id']
				);	
				 $r = create_logs_from_array_of_array($arr);
				 
				$_log_id=$r['tbl_reg_logs'];
				if(!empty($_log_id) && $rm_arr['first_log_id']=='')
				{
					$_newUpdtArr['tbl_reg_logs']['first_log_id']=$_log_id;
					update_table_from_array_of_array($_newUpdtArr,$_log_id);					
				}
				
			//updateTbltbl_updated_reg_logs($memid);

            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'=>'MA',
            '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,
            'amountWOTax'=>$price,
            'created_on'=>$GLOBALS['currDateTime'],
			'lead_type'=>$lead_type,
			'fudate'=>$fudate,
			'rm'=>$rm_arr['rm_id'],
			'subrm'=>$rm_arr['subrm_id'],
			'mood'=>$mood,
			'no_of_memids' => 1,
			'pipeline_status'=>'New',
			'routing_status'=>$lead_type,
			'first_log_id' => $rm_arr['first_log_id']
			);	
			 $r = create_logs_from_array_of_array($arr);
			 
			$_log_id=$r['tbl_reg_logs'];
			if(!empty($_log_id) && $rm_arr['first_log_id']=='')
			{
				$_newUpdtArr['tbl_reg_logs']['first_log_id']=$_log_id;
				update_table_from_array_of_array($_newUpdtArr,$_log_id);					
			}
       // $_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['reglogs_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'] =  BASEURL."pay/commonCheckOut.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'] =  BASEURL."paypal/common_payment.php";
            else
                $pymtURLToredirectTo = $_result['pymtURLToredirectTo'] =  BASEURL."paypal/common_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" => BASEURL.'/successfullpayment_offer.php?name='.$payment_details_arr['billing_name'].'&plan='.$payment_details_arr['merchant_param5']);
            //return $redirecturl  =BASEURL.'/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  =BASEURL.'/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=$arr['bank_name'];
        list($merchant_param5, $merchant_param6, $promopage) = explode(',', $arr['merchant_param5']);

        if( strpos(strtoupper($arr['order_id']), "EVENTS") !== false  ){
			
			
            $fetch_user_data =mysql_fetch_array(mysql_query("select name,
				CASE
				   WHEN send_sms_to = 'R' THEN phoneno
				   ELSE alternate_mob_no
				END as phoneno,
				case 
					when send_email_to = 'R' then email 
					else addtnl_email 
				end as communication_email
				from tbl_members where id = ".$memid), MYSQL_ASSOC);
			
			$event_id = qryToCommaSepString("select event_id from tbl_sm_events_payment_details where id =" .$reg_log_id);
			
            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.";
				
				$reglog_update = mysql_query("update tbl_sm_events_payment_details set pymt_details	='CCAVENUE', pym_Mode='NEFT/Online', status='Pending',paymentstatus='failed',comments='failed transaction'  where id =" . $reg_log_id);	
					
				onUnsuccesfulPymtEvents($email=$fetch_user_data['communication_email'], $reg_log_id, $name=$fetch_user_data['name'], $event_id);
					
            }elseif($pymtStatus==="Success"){
                $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);

                onEventSuccessfulTranscation("online", $reg_log_id, $final_inv_no);
               /*  $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['name'], $fetch_user_data['communication_email'], $memid,  $fetch_user_data['phoneno'], $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=BASEURL."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'] =  "12500" ;
    }

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


    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 ('/home/steelmin/public_html/inc/desconfig.php');

?>
