<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Secure Card Save</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background-color: #fff8f9; font-family: 'Helvetica Neue', sans-serif; }
    .container { max-width: 550px; margin-top: 60px; padding: 30px; background: white; border-radius: 15px; box-shadow: 0 0 20px rgba(0,0,0,0.1); }
    h2 { color: #d99ba8; }
    button { background-color: #d99ba8; color: white; border: none; }
    button:hover { background-color: #c27a8f; }
  </style>
</head>
<body>
<div class="container">
  <h2 class="text-center mb-4">Enter Your Info & Save Card</h2>
  <form id="full-form">
    <div class="mb-3">
      <label>Name</label>
      <input type="text" id="name" class="form-control" required>
    </div>
    <div class="mb-3">
      <label>Email</label>
      <input type="email" id="email" class="form-control" required>
    </div>
    <div class="mb-3">
      <label>Card Details</label>
      <div id="card-element" class="form-control p-2"></div>
    </div>
    <div id="card-errors" class="text-danger mb-3"></div>
    <button type="submit" class="btn w-100">Save Card</button>
  </form>
  <div id="result-message" class="alert mt-3 d-none"></div>
</div>

<script src="https://js.stripe.com/v3/"></script>
<script>
  const stripe = Stripe('pk_test_51HoV0JFFWbjoruwt8TbFsfFe71woYakmZEeNqqCNk3BFTrVphrefaXRuVh95JEvJx0IcF6ikd5ZjaflU7uFWPBuC001B1Y4p8a');
  const elements = stripe.elements();
  const card = elements.create('card');
  card.mount('#card-element');

  document.getElementById('full-form').addEventListener('submit', async (e) => {
    e.preventDefault();

    const name = document.getElementById('name').value;
    const email = document.getElementById('email').value;

    // Step 1: Send name/email to server
    const res = await fetch('create-setup-intent.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({ name, email })
    });

    const data = await res.json();
    const clientSecret = data.clientSecret;

    // Step 2: Confirm card setup
    const { setupIntent, error } = await stripe.confirmCardSetup(clientSecret, {
      payment_method: {
        card: card,
        billing_details: {
          name: name,
          email: email,
        },
      }
    });

    const resultDiv = document.getElementById('result-message');
    if (error) {
      document.getElementById('card-errors').textContent = error.message;
    } else {
      resultDiv.classList.remove('d-none');
      resultDiv.classList.add('alert-success');
      resultDiv.innerHTML = "Card saved!<br>Payment Method ID: <strong>" + setupIntent.payment_method + "</strong>";
    }
  });
</script>
</body>
</html>
