<?php

if (is_file(realpath('../system/stripe-php/init.php'))) {
  require_once(realpath('../system/stripe-php/init.php'));
}

$stripe = new \Stripe\StripeClient('sk_live_wz1r8mYdFPWPPAMLDrFMrj4P'); //sk_live_wz1r8mYdFPWPPAMLDrFMrj4P

header('Content-Type: application/json');

try {
  // Retrieve JSON from POST body
  $json_str = file_get_contents('php://input');
  $json_obj = json_decode($json_str);

  // Attach payment method to customer
  $payment_method = $stripe->paymentMethods->retrieve($json_obj->paymentMethodId);
  $payment_method->attach(['customer' => $json_obj->customerId]);

  // Set the default payment method on the customer
  $stripe->customers->update($json_obj->customerId, [
    'invoice_settings' => ['default_payment_method' => $json_obj->paymentMethodId],
  ]);

  echo json_encode(['success' => 'Payment method attached and set as default']);

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