<?php require_once('includes/check-login.php');
require_once('includes/config.php');
require_once('email.php');
$tablename="subscription";
$viewurl="subscription.php";
if(isset($_POST)){
	$response = $_POST;
	
	/* It is very important to calculate the hash using the returned value and compare it against the hash that was sent while payment request, to make sure the response is legitimate */
	$salt = "";
	$result=$con->query("SELECT * from payment_settings");
    if(mysqli_num_rows($result)>0){
     $payrow=mysqli_fetch_array($result);
     $salt=$payrow['salt_key']; /* put your salt provided by Basispay here */
    }
	if(isset($salt) && !empty($salt)){
		$response['calculated_hash']=hashCalculate($salt, $response);
		$response['valid_hash'] = ($response['hash']==$response['calculated_hash'])?'Yes':'No';
		$response_code=$response['response_code']; 
		if(!empty($response_code)){
		if($response_code==1073 || $response_code==0){
		$amount=$response['amount'];    
		$response_message=$response['response_message'];
		$created=date("Y-m-d");
        $user_id=$_SESSION['userid'];
        $role_id=$_SESSION['role_id'];
        $expiry_date=date('Y-m-d',strtotime('+1 year',strtotime($created)));
        $getvendor=$con->query("SELECT * FROM user_details WHERE user_id='$user_id'");
        $getrow=mysqli_fetch_array($getvendor);
        if($role_id==2){
        $query="insert into ".$tablename." SET vendor_id='".$user_id."',amount='".$amount."',description='Yearly Subscription added successfully',date='".$created."',expiry_date='".$expiry_date."'";
		$exe = mysqli_query( $con, $query );
		
		$payment=mysqli_query( $con,"insert into payment_transaction SET order_id='".$response['order_id']."',name='".$response['name']."',transaction_id='".$response['transaction_id']."',payment_mode='".$response['payment_mode']."',payment_channel='".$response['payment_channel']."',payment_datetime='".$response['payment_datetime']."',amount='".$amount."'");
		
		if( $exe ) {	
		    $html=' <h1>Hi '.$getrow['name'].',</h1> 
            <p>Your Yearly subscription has been activated successfully till valid on <b>'.$expiry_date.'</b></p>';
           sendemail($getrow['email'],"Yearly subscription",$html);
			$_SESSION[$tablename.'succ_msg'] = 'Yearly Subscription added successfully';
			header("Location:".$base_url.$viewurl."");
		}else{				
			$_SESSION[$tablename.'err_msg'] = 'Error occured';
		}}else{
		 $_SESSION[$tablename.'err_msg'] = "You aren't a Service Provider";   
		}
		}else{
		 $response_message=$response['response_message'];   
		 $_SESSION[$tablename.'err_msg'] = $response_message;   
		}
		}
	} else {
		$response['valid_hash']='Set your salt in return_page.php to do a hash check on receiving response from Basispay';
	}
}

function hashCalculate($salt,$input){
	/* Remove hash key if it is present */
	unset($input['hash']);
	/*Sort the array before hashing*/
	ksort($input);
	
	/*first value of hash data will be salt*/
	$hash_data = $salt;
	
	/*Create a | (pipe) separated string of all the $input values which are available in $hash_columns*/
	foreach ($input as $key=>$value) {
		if (strlen($value) > 0) {
			$hash_data .= '|' . $value;
		}
	}

	$hash = null;
	if (strlen($hash_data) > 0) {
		$hash = strtoupper(hash("sha512", $hash_data));
	}
		
	return $hash;
}
$display = "Add";
$settings=$con->query("SELECT monthly_balance FROM wallet_settings"); 
$row=mysqli_fetch_array($settings);
$monthly_balance=$row['monthly_balance']; 

$user_id=$_SESSION['userid'];
$date=date("Y-m-d");
$validsub=$con->query("SELECT id,date,vendor_id,expiry_date FROM subscription WHERE vendor_id='".$user_id."' and date(expiry_date)>='$date' order by id desc limit 0,1");  
$validrow=mysqli_fetch_array($validsub);
if(mysqli_num_rows($validsub)>0){
    $valid_date=$validrow['expiry_date'];
    $due_date=date('M,d Y',strtotime($valid_date)); 
    $message="Subscription Valid till <span style='color:green'>$due_date</span>";
}else{
   $message="Subscription Expired.Please add subscription"; 
}
require_once('includes/header.php');
require_once('includes/menu.php'); ?>
<!------ Include the above in your HEAD tag ---------->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
      <!-- Content Header (Page header) -->
            <section class="content-header">                               
                    <ol class="breadcrumb">
                        <li><a href="<?php echo $base_url;?>"><i class="fa fa-dashboard"></i>Home</a></li>                    
                        <li class="active"><a href="#">Subscription</a></li>           
                    </ol>                
            </section>
<form action="subscriberequest.php" id="payment_form" method="GET">
    <div class="row setup-content">
      <div class="col-xs-6 col-md-offset-3">
        <div class="col-md-12">
            <center><h3>Subscription</h3></center>
            <center><b><?php echo $message;?></b></center>
            <center></center><?php if(isset($_SESSION[$tablename."succ_msg"])) {?>
                 <div class="alert alert-success">
                 <a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">×</a>
                 <?php echo $_SESSION[$tablename."succ_msg"];  unset($_SESSION[$tablename."succ_msg"]);?>
                 </div>
                <?php }?>   
                <?php if(isset($_SESSION[$tablename."err_msg"])) {?>
                <div class="alert alert-success">
                <a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">×</a>
                <?php echo $_SESSION[$tablename."err_msg"]; unset($_SESSION[$tablename."err_msg"]);?>
                </div>
               <?php }?></center>
                <input  id="amount" name="amount" value="<?php echo $monthly_balance;?>" type="hidden" min="1" class="form-control" placeholder="Enter Amount"  />
              <?php if(mysqli_num_rows($validsub)==0){?>

              <div class="col-md-12">
               <center><div class="form-group" style="margin-top: 15px;">
                <button class="btn btn-success btn-lg" type="submit" name="submit">Add Subscription</button></center>
              </div> 
              </div>
              <?php }?>
            
        </div>
      </div>
    </div>
  </form>
</div>
<script src="js/common.js"></script>  
<script src="<?php echo $base_url;?>js/jquery-3.4.1.min.js"></script>
<script src="<?php echo $base_url;?>js/jquery.validate.min.js"></script>
<script type="text/javascript">
$(function(){
       $("#payment_form").validate({
          rules: {
               amount: 'required',
           },
            messages: {
                                    
            },
            submitHandler: function(form) {
              form.submit();
           }
    });        
});
</script>
<?php require_once('includes/footer.php'); ?>