<?php
session_start(); 
require('includes/db_config.php');
?>
<?php
//check if stripe token exist to proceed with payment
if(isset($_POST['stripeToken'])){
    // get token and user details
var_dump($_POST);
    $stripeToken  = $_POST['stripeToken'];
    $custName = $_POST['name'];
    $custEmail = $_POST['email'];
    $cardNumber = $_POST['cardNumber'];
    $cardCVC = $_POST['cardCVC'];
    $cardExpMonth = $_POST['cardExpMonth'];
    $cardExpYear = $_POST['cardExpYear'];    
    $paym_id = $_POST['paym_id'];
    //include Stripe PHP library
    require_once('stripe-php/init.php');    
    //set stripe secret key and publishable key
    $stripe = array(
      "secret_key"      => "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",
      "publishable_key" => "pk_live_51IQcHgJQjTHmTj5DnekX7CgybiiLGJNtq4F8egmLZkUdQZ6iUf2RgN9lhuVWaKRJ0zUNAowr3eLCuK87OMuXcTNA00pjjDuuW7"
    );    
    \Stripe\Stripe::setApiKey($stripe['secret_key']);    
    //add customer to stripe
    $customer = \Stripe\Customer::create(array(
        'email' => $custEmail,
        'source'  => $stripeToken
    ));    
    $sql=mysqli_query($conn, "select * from user_payment where id='".$paym_id."'");
    $row=mysqli_fetch_array($sql);
    $sql1=mysqli_query($conn, "select * from user_profile where id=".$_SESSION['user_id']);
    $row1=mysqli_fetch_array($sql1);
    $total_price = $row['total_price']; 
    $order_id = $row['order_id']; 
    $pid = $row['id'];
    // item details for which payment made
    $itemName = "Orange Groceries";
    $itemNumber = "Angstripe54321";
    $itemPrice = $total_price * 100;
    $currency = "INR";
    $orderID = $order_id;    
    // details for which payment performed
    $payDetails = \Stripe\Charge::create(array(
        'customer' => $customer->id,
        'amount'   => $itemPrice,
        'currency' => $currency,
        'description' => $itemName,
        'metadata' => array(
            'order_id' => $orderID
        )
    ));    
    // get payment details
    $paymenyResponse = $payDetails->jsonSerialize();
    // check whether the payment is successful
    if($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1){
        // transaction details 
        $amountPaid = $paymenyResponse['amount'];
        $balanceTransaction = $paymenyResponse['balance_transaction'];
        $paidCurrency = $paymenyResponse['currency'];
        $paymentStatus = $paymenyResponse['status'];
        $paymentDate = date("Y-m-d H:i:s");        
        //insert tansaction details into database
        $plan_id = $row['cart_id'];
    $name = $row1['fname'];
    $user_id = $_SESSION['user_id'];
    $rid = explode(",",$plan_id);
    foreach($rid as $pm_id){
     $status="1";
     $sql_paytm ="UPDATE  addto_cart SET payment_status='$status' WHERE user_id='".$user_id."' and id='".$pm_id."'"; 
    $result_ptm=mysqli_query($conn,$sql_paytm) or die(mysqli_error());
    }
    $payment_method="stripe";
    date_default_timezone_set('Asia/Kolkata');
    $created_at = date( 'Y-m-d h:i:s A', time () );
    $statuss=1;
    $sql_pay ="UPDATE  user_payment SET card_number='$cardNumber',card_cvc='$cardCVC',card_exp_month='$cardExpMonth',card_exp_year='$cardExpYear',item_number='$itemNumber',paid_amount_currency='$paidCurrency',payment_method='$payment_method',pay_status='$paymentStatus',paid_amount='$amountPaid',transactionId='$balanceTransaction',payable_status='$statuss',created_date='$created_at' WHERE id='".$paym_id."'"; 
    echo $sql_pay; exit();    
        mysqli_query($conn, $sql_pay) or die("database error: ". mysqli_error($conn));
        $lastInsertId = $paym_id; 
       //if order inserted successfully
       if($lastInsertId && $paymentStatus == 'succeeded'){
            header("location:invoice.php?id=".$pid);
       } else{
       echo "<script> 
                alert('Payment failed!!!!'); 
                location.replace('index.php');
            </script>";       }
    } else{
 echo "<script> 
                alert('Amount Failed Payment failed!!!!'); 
                location.replace('index.php');
            </script>";           }
} else{
 echo "<script> 
                alert('Card Not Found ! Payment failed!!!!'); 
                location.replace('stripe-payment.php');
            </script>";       }
