<?php
session_start();

if (!isset($_SESSION['id']) ) {
    header("location: ../index.php");
}

?>


<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Merchant</title>
    <meta name="viewport" content="width=device-width" ,="" initial-scale="1.0/">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrom=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

	<script src="js/jquery-1.8.3.min.js"></script>
    <script id = "myScript" src="https://scripts.pay.bka.sh/versions/1.2.0-beta/checkout/bKash-checkout.js"></script> 
   <!--  <script id = "myScript" src="https://scripts.sandbox.bka.sh/versions/1.2.0-beta/checkout/bKash-checkout-sandbox.js"></script>-->
    <!-- sweet alert  -->
  <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>

<div class="container">
  <div class="row">
     <div class="col-md-12 col-lg-12 col-sm-12">
       <div class="card" style="margin-top: 30px;">
           <h1 style="text-align: center;">Notre Dame College</h1>

           
 
       <button id="bKash_button" class="btn btn-success">Pay With bKash</button>
       </div>
     
     </div>
  </div>

</div>



<script type="text/javascript">
 
    var accessToken='';
    $(document).ready(function(){
        $.ajax({
            url: "token.php",
            type: 'POST',
            contentType: 'application/json',
            success: function (data) {
                console.log('got data from token  ..');
				//console.log(JSON.stringify(data));
				
                accessToken=JSON.stringify(data);
            },
			error: function(){
						console.log('error');
                        
            }
        });

        var paymentConfig={
            createCheckoutURL:"createpayment.php",
            executeCheckoutURL:"executepayment.php"
        };

		
        var paymentRequest;
        paymentRequest = { amount:'10',intent:'sale'};
		console.log('out-'+JSON.stringify(paymentRequest));

        bKash.init({
            paymentMode: 'checkout',
            paymentRequest: paymentRequest,
            createRequest: function(request){
                console.log('=> createRequest (request) :: ');
                console.log(request);
                
                $.ajax({
                    // url: "createpayment.php?amount=10",
                    url: "createpayment.php?amount="+paymentRequest.amount,
                    type:'GET',
                    contentType: 'application/json',
                    success: function(data) {
                        console.log('got data from create  ..');
                        console.log('data ::=>');
                        console.log(data);
                        console.log(JSON.stringify(data));
                        
                        var obj = JSON.parse(data);
                        
                        if(data && obj.paymentID != null){
                            paymentID = obj.paymentID;
                            bKash.create().onSuccess(obj);
                        }
                        else {
							console.log('error');
                            bKash.create().onError();
                        }
                    },
                    error: function(){
						console.log('error');
                        bKash.create().onError();
                    }
                });
            },
            
            executeRequestOnAuthorization: function(){
		//timeout=setTimeout(alertFunc, 30000);
                console.log('=> executeRequestOnAuthorization');
                $.ajax({
                    url: paymentConfig.executeCheckoutURL+"?paymentID="+paymentID,
                    type: 'GET',
                    contentType:'application/json',
                    success: function(data){
                        console.log('got data from execute  ..');
                        console.log('data ::=>');
                        console.log(JSON.stringify(data)); 
                        data = JSON.parse(data);                       
                        console.log('merchantInvoiceNumber:='+data.merchantInvoiceNumber);                       
                        console.log('paymentId:='+data.paymentID);
                        if(data && data.paymentID != null){
                            //alert('[SUCCESS] data : ' + JSON.stringify(data));
                            // window.location.href = "success.html";  
                            $.ajax({
                              url: "insertPayment.php?p_APP_ROLL_NO="+<?php echo $_SESSION['APP_ROLL_NO']; ?>+"&p_PAYMENT_ID="+data.paymentID+"&p_TRX_ID="+data.trxID+"&p_TRX_STATUS="+data.transactionStatus+"&p_AMOUNT="+data.amount+"&p_CURRENCY="+data.currency+"&p_INTENT="+data.intent+"&p_INV_NO="+data.merchantInvoiceNumber+"&p_MSISDN="+data.customerMsisdn+"&p_TRX_DATE="+data.createTime,
                              success: function(output) {
                                $('.result').html(output);
                                output = JSON.parse(output);
                                if(output.result===1){
                                    //console.log('insertPayment ::=>'+output.result);
                                    //window.location.href = "../view1.php"; 
                                    //window.location.href = "../pay_sleep.php";
                                }                               
                              }
                            });           
                                                         
                        }else if(data && data.errorCode != null){
                        	if(data.errorCode==='2029'){
                        	   console.log('errorMessage:='+data.errorMessage);
                        	   //window.location.href = "payment.php";
                        	   bKash.execute().onError();
                        	   deleteContent();
                        	}
                        }
                        else {
                            $.ajax({
                            url: "querypayment.php?paymentID="+paymentID,
                            type: 'GET',
                            contentType:'application/json',
                            success: function(sdata){
                                console.log('query ::=>');
                            console.log(JSON.stringify(sdata));
                            sdata = JSON.parse(sdata); 
                            if(sdata && sdata.trxID != null){
                                $.ajax({
                                url: "insertPayment.php?p_APP_ROLL_NO="+<?php echo $_SESSION['APP_ROLL_NO']; ?>+"&p_PAYMENT_ID="+data.paymentID+"&p_TRX_ID="+data.trxID+"&p_TRX_STATUS="+data.transactionStatus+"&p_AMOUNT="+data.amount+"&p_CURRENCY="+data.currency+"&p_INTENT="+data.intent+"&p_INV_NO="+data.merchantInvoiceNumber+"&p_MSISDN="+data.customerMsisdn+"&p_TRX_DATE="+data.createTime,
                                success: function(output) {
                                    $('.result').html(output);
                                    output = JSON.parse(output);
                                    if(output.result===1){
                                        //console.log('insertPayment ::=>'+output.result);
                                        //window.location.href = "../view1.php"; 
                                        //window.location.href = "../pay_sleep.php";
                                    }                               
                                }
                                }); 
                            }else{
                                bKash.execute().onError();
                        	    queryContent();
                            }
                            /*$.ajax({
                                url: "searchpayment.php?paymentID="+sdata.trxID,
                                type: 'GET',
                                contentType:'application/json',
                                success: function(data){
                                    console.log('search ::=>');
                                console.log(JSON.stringify(data)); 
                                }
                            });*/
                            }
                            });
                        }
                        
                    },
                    error: function(){
                        bKash.execute().onError();
                    }
                });
                
                /*function alertFunc() {
		    $.ajax({
		    url: "querypayment.php?paymentID="+paymentID,
		    type: 'GET',
		    contentType:'application/json',
		    success: function(data){
		    	console.log('query ::=>');
		        console.log(JSON.stringify(data)); 
		    }
		    });
		}*/
            }
        });
        
		console.log("Right after init ");
    
        
    });
	
	function callReconfigure(val){
        bKash.reconfigure(val);
    }

    function clickPayButton(){
        $("#bKash_button").trigger('click');
    }
function deleteContent() {
            Swal.fire({
                icon: 'error',
                title: 'Payment Failed!',
                text: 'Duplicate for All Transactions',

            })
        }
        function queryContent() {
            Swal.fire({
                icon: 'error',
                title: 'Payment Failed!',
                text: 'Try Again',

            })
        }
	
</script>
    
</body>
</html>

