<?php
header("content_type:application/json");
error_reporting(1);
use \dapi\StripePayment;
include_once 'dbconnect.php';
include_once '../stripe/stripe-php/init.php';

$publishablekey='pk_test_8Y9dUoiTBgcZgqM5BoD2u9Hd00fxWqNzn6';
session_start();
$_SESSION['uid'];
$_SESSION['cardname'];
$_SESSION['cardnumber'];
$_SESSION['expmonth'];
$_SESSION['expyear'];
$_SESSION['cvc'];
$_SESSION['amount'];
$_SESSION['proid'];
 if(!empty($_SESSION['uid'])) {

    $userid=$_SESSION['uid'];
    $username=$_SESSION['cardname'];
    $email=$_GET['email'];
    $mobile=$_GET['mobile'];
    $address=$_GET['address'];
    $productid=$_GET['productid'];
    $quantity=$_GET['quantity'];
    $price=$_GET['netprice'];
    $payment=$_SESSION['amount'];
    $cardname=$_SESSION['cardname'];
    $cardnumber=$_SESSION['cardnumber'];
    $expmonth=$_SESSION['expmonth'];
    $expyear=$_SESSION['expyear'];
    $cvc=$_SESSION['cvc'];
// $query="INSERT INTO cart (user_id, product_id, quantity) values ('$userid','$productid','$quantity')";
// $result=mysqli_query($con,$query);


//      $query="SELECT * FROM cart WHERE user_id='$userid')";
// $result1=mysqli_query($con,$query);
// if(mysqli_num_rows($result1) > 0){

//   while($row = mysqli_fetch_array($result1)){
//      array_push($response,

//      array(
//          'id' => $row['id'],
//          'userid' => $row['user_id'],
//          'productid' => $row['product_id'],
//          'quantity' => $row['quantity'],
        
//       )

//  );
        
//  }
//  echo json_encode($response);
    
// }
//  else{

//      $resoponse="Cart is empty";
//      echo $response;
//  }
    if (!empty($_POST["token"])) {
    require_once './StripePayment.php';
    $stripePayment = new StripePayment();
    
    $stripeResponse = $stripePayment->chargeAmountFromCard($_POST);
    
    // require_once "DBController.php";
    // $dbController = new DBController();
    
    $amount = $stripeResponse["amount"] /100;
    
    $param_type = 'ssssssdssss';
    $products_arr["records"]=array();
    $param_value_array = array(
        "name"=>$_POST['name'],
        "address"=>$_POST['address'],
        "productid"=>$_POST['productid'],
        "quantity"=>$_POST['quantity'],
        "email"=> $_POST['email'],
        "item_number"=>$_POST['item_number'],
        "payment" => $amount,
        $stripeResponse["currency"],
        "txnid"=>$stripeResponse["balance_transaction"],
        $stripeResponse["status"],
        // json_encode($stripeResponse)
    );
    // $query = "INSERT INTO tbl_payment (email, item_number, amount, currency_code, txn_id, payment_status, payment_response) values (?, ?, ?, ?, ?, ?, ?)";
    // $id = $dbController->insert($query, $param_type, $param_value_array);
     array_push($products_arr["records"], $param_value_array);
    if ($stripeResponse['amount_refunded'] == 0 && empty($stripeResponse['failure_code']) && $stripeResponse['paid'] == 1 && $stripeResponse['captured'] == 1 && $stripeResponse['status'] == 'succeeded') {
        $successMessage = "Stripe payment is completed successfully. The TXN ID is " . $stripeResponse["balance_transaction"];

        echo json_encode($products_arr);
       
    }
}

}

?>
<!DOCTYPE html>
<html>
<head>  
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function cardValidation () {
    var valid = true;
    var userid = "<?php echo $userid ?>";
    // var productid = "<?php echo $productid ?>";
    // var quantity = "<?php echo $quantity ?>";
    // var price = "<?php echo $price ?>";
    // var payment = "<?php echo $payment ?>";
    var cardname = "<?php echo $cardname ?>";
    var cardNumber = "<?php echo $cardnumber ?>";
    var month = "<?php echo $expmonth ?>";
    var year = "<?php echo $expyear ?>";
    var cvc = "<?php echo $cvc ?>";

    if (userid.trim() == "") {
        valid = false;
    }
    // if (productid.trim() == "") {
    //     valid = false;
    // }
    if (cardNumber.trim() == "") {
           valid = false;
    }

    // if (price.trim() == "") {
    //      valid = false;
    // }
    // if (payment.trim() == "") {
    //     valid = false;
    // }
    if (cvc.trim() == "") {
        valid = false;
    }
    // if (quantity.trim() == "") {
    //     valid = false;
    // }
    // if (cardname.trim() == "") {
    //     valid = false;
    // }
    if (month.trim() == "") {
        valid = false;
    }
    if (year.trim() == "") {
        valid = false;
    }

     if(valid == false) {
        alert("All fields are required");
    }

    return valid;
}
//set your publishable key
Stripe.setPublishableKey("<?php echo $publishablekey ?>");

//callback to handle the response from stripe
function stripeResponseHandler(status, response) {
    if (response.error) {
        //enable the submit button
       alert("error in payment");
        console.log(response);
    } else {
        //_GET token id
        var token = response['id'];
        //insert the token into the form
        $("#frmStripePayment").append("<input type='hidden' name='token' value='" + token + "' />");
        //submit form to the server
        $("#frmStripePayment").submit();
    }
}
function stripePay(e) {
    e.preventDefault();
    var valid = cardValidation();

    if(valid == true) {
        Stripe.createToken({
            number: <?php echo $cardnumber ?>,
            cvc: <?php echo $cvc ?>,
            exp_month: <?php echo $expmonth ?>,
            exp_year: <?php echo $expyear ?>
        }, stripeResponseHandler);

        //submit from callback
        return false;
        console.log(stripeResponseHandler);
    }
}
</script>
</head>
<body onload="stripePay(event)">
<form id="frmStripePayment" action="ordercall.php" method="POST">
<input type="hidden" name="card-number" value="<?php echo $cardnumber ?>">
<input type="hidden" name="cvc" value="<?php echo $cvc ?>">
<input type="hidden" name="month" value="<?php echo $expmonth ?>">
<input type="hidden" name="year" value="<?php echo $expyear ?>">
<input type='hidden' name='amount' value='<?php echo $price ?>'> 
<input type='hidden' name='currency_code' value='USD'> 
<input type='hidden' name='item_name' value='Test Product'> 
<input type='hidden' name='item_number' value='PHPPOTEG#1'>
<input type='hidden' name='name' value="<?php echo $username ?>"> 
<input type='hidden' name='address' value="<?php echo $address ?>"> 
<input type='hidden' name='productid' value="<?php echo $productid ?>"> 
<input type='hidden' name='quantity' value="<?php echo $quantity ?>">
<input type="hidden" name="email" value="<?php echo $email ?>">
</form>
</body>
</html>
