<?php
$amount=$_GET["amount"];
$artist_id=$_GET["artist_id"];
$date=$_GET["date"];
$start_time_org=$_GET["start_time_org"];
$end_time_org=$_GET["end_time_org"];
$book_id=$_GET["book_id"];
// var_dump($_GET);

if($_GET["self"]==1)
{


  require_once('../include/stripe-php-7.95.0/stripe-php-7.95.0/init.php');

  \Stripe\Stripe::setApiKey('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');
  //\Stripe\Stripe::setApiKey('sk_test_51JVYIJB4E9A8AkDupK7tK280LNgVpc7mgTkRrCtvPqyWvpSFNFT3NkGxQLWQzCUkEnWKxnV24lRPFxbSmtjPB8ZH00jiHmf1jf');

  header('Content-Type: application/json');
  //$YOUR_DOMAIN = 'http://localhost:4242/public';

  try {

  $paymentIntent = \Stripe\PaymentIntent::create([
    'amount' => (int)($amount*100),
    'currency' => 'gbp',
  ]);
  //echo "here i try";
  $output = [
    'clientSecret' => $paymentIntent->client_secret,
  ];

  //print_r($output);
  echo json_encode($output);
  } catch (Error $e) {

  http_response_code(500);
  echo json_encode(['error' => $e->getMessage()]);
  }
  die();
}

// $checkout_session = \Stripe\Checkout\Session::create([
//   'line_items' => [[
//     # TODO: replace this with the `price` of the product you want to sell
//     'price_data' => [
//         'unit_amount' => (int)($amount*100),
//         'currency' => 'gbp',
//         'product_data' =>[
//             'name' =>$book_id."~".$start_time_org."~".$end_time_org."~".$artist_id."~".$date
//         ]
//     ],
//     'quantity' => 1,
//   ]],
//   'payment_method_types' => [
//     'card',
//   ],
//   'mode' => 'payment',
//   'success_url' => 'http://178.79.159.161/book.tapnstyle.com/newapp/api/successpayment.php?errorcode=0&orderreference='.$book_id."~".$start_time_org."~".$end_time_org."~".$artist_id."~".$date,
//   'cancel_url' => 'http://178.79.159.161/book.tapnstyle.com/newapp/api/successpayment.php?errorcode=1',
// ]);
//die($checkout_session->url);
// header("HTTP/1.1 303 See Other");
// header("Location: " . $checkout_session->url);
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Accept a card payment</title>
    <meta name="description" content="Card payment on Stripe" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="card.css" />
    <script src="https://js.stripe.com/v3/"></script>
    <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    <!-- <script src="client.js" defer></script> -->
  </head>
  <body style="background:#fff;">
    <!-- Display a payment form -->
    <form id="payment-form">
      <div id="card-element"><!--Stripe.js injects the Card Element--></div>
      <button id="submit">
        <div class="spinner hidden" id="spinner"></div>
        <span id="button-text">Pay now</span>
      </button>
      <p id="card-error" role="alert"></p>
      <p class="result-message hidden">
        Payment succeeded!!
      </p>
    </form>
  </body>
</html>
<?php
 // echo "<script>   document.forms['frm'].submit();  </script> ";
/*$artist_status = get_single_value('tp_artist','status','a_id='.$artist_id,'a_id','desc','limit 1',false);
if($artist_status=='1')
{

    $check_qry = "SELECT * FROM `tp_booking_schedule` where ( artist_id='".$artist_id."'  and date='".$date."') and   (('".$start_time."' BETWEEN start_time and end_time) or ('".$end_time."' BETWEEN start_time and end_time))  ";
    $data_qry = mysql_query($check_qry);
    $row_count = mysql_num_rows($data_qry);
     //echo "Count :- ".$row_count;
    if($row_count > 0 )
    {
    	$data = 'Artist is Busy';
    }
    else
    {
        $data = 'Submit Form Data';

    }
}
elseif($artist_status=='0')
{
	$data = 'Artist Inactive';
}
else
{
	$data = "Do Something";
}

echo $data;*/


?>

<script type="text/javascript">
    //location.href="http://book.tapnstyle.com/Booking/success";
   // var stripe = Stripe("pk_test_51JVYIJB4E9A8AkDuL8VdM6lNA1xWsbjjufbNKNZSV5MSe17Wv0lJhjMqgbHgzc4KCuDZZlEnpjG9CCc2M986Mdhe00sGVWb8fx");
    var stripe = Stripe("pk_live_51JVYIJB4E9A8AkDu3G6NWysTSFbYODewijm6vQek0tYfup8v4YMJOVtlNOv2HLNefyYh3xxkNRljnWbdaqUk6au700Rjo1JhYw");

// The items the customer wants to buy
var purchase = {
  items: [{ id: "xl-tshirt" }]
};

// Disable the button until we have Stripe set up on the page
document.querySelector("button").disabled = true;
fetch('<?php echo "paymentfrm.php?self=1&amount=".$amount."&artist_id=".$artist_id."&start_time=".$start_time_org."&date=".$date."&start_time_org=".$start_time_org."&end_time_org=".$end_time_org."&book_id=".$book_id ?>', {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(purchase)
})
  .then(function(result) {
    return result.json();
  })
  .then(function(data) {
    var elements = stripe.elements();

    var style = {
      base: {
        color: "#32325d",
        fontFamily: 'Arial, sans-serif',
        fontSmoothing: "antialiased",
        fontSize: "16px",
        "::placeholder": {
          color: "#32325d"
        }
      },
      invalid: {
        fontFamily: 'Arial, sans-serif',
        color: "#fa755a",
        iconColor: "#fa755a"
      }
    };

    var card = elements.create("card", { style: style });
    // Stripe injects an iframe into the DOM
    card.mount("#card-element");

    card.on("change", function (event) {
      // Disable the Pay button if there are no card details in the Element
      document.querySelector("button").disabled = event.empty;
      document.querySelector("#card-error").textContent = event.error ? event.error.message : "";
    });

    var form = document.getElementById("payment-form");
    form.addEventListener("submit", function(event) {
      event.preventDefault();
      // Complete payment when the submit button is clicked
      payWithCard(stripe, card, data.clientSecret);
    });
  });

// Calls stripe.confirmCardPayment
// If the card requires authentication Stripe shows a pop-up modal to
// prompt the user to enter authentication details without leaving your page.
var payWithCard = function(stripe, card, clientSecret) {
  loading(true);
  stripe
    .confirmCardPayment(clientSecret, {
      payment_method: {
        card: card
      }
    })
    .then(function(result) {
      if (result.error) {
        // Show error to your customer
        showError(result.error.message);
      } else {
        // The payment succeeded!
        orderComplete(result.paymentIntent.id);
      }
    });
};

/* ------- UI helpers ------- */

// Shows a success message when the payment is complete
var orderComplete = function(paymentIntentId) {
  loading(false);
  // document
  //   .querySelector(".result-message a")
  //   .setAttribute(
  //     "href",
  //     "https://dashboard.stripe.com/test/payments/" + paymentIntentId
  //   );
  document.querySelector(".result-message").classList.remove("hidden");
  document.querySelector("button").disabled = true;
  location.href="<?php echo "http://178.79.159.161/book.tapnstyle.com/newapp/api/successpayment.php?errorcode=0&orderreference=".$book_id."~".$start_time_org."~".$end_time_org."~".$artist_id."~".$date ?>";
};

// Show the customer the error from Stripe if their card fails to charge
var showError = function(errorMsgText) {
  loading(false);
  var errorMsg = document.querySelector("#card-error");
  errorMsg.textContent = errorMsgText;
  setTimeout(function() {
    errorMsg.textContent = "";
  }, 4000);
};

// Show a spinner on payment submission
var loading = function(isLoading) {
  if (isLoading) {
    // Disable the button and show a spinner
    document.querySelector("button").disabled = true;
    document.querySelector("#spinner").classList.remove("hidden");
    document.querySelector("#button-text").classList.add("hidden");
  } else {
    document.querySelector("button").disabled = false;
    document.querySelector("#spinner").classList.add("hidden");
    document.querySelector("#button-text").classList.remove("hidden");
  }
};
</script>
<?php /**PATH /Applications/MAMP/htdocs/carhire/resources/views/checkout.blade.php ENDPATH**/ ?>