<template>
<div class="modal-prompt">

<section class="shadowbox">
<h2>Update Billing</h2>
<prompt v-if="step == 1" :err="err" @ok="() => step++" />
<billing v-if="step == 2" :err="err" :sub="user.sub"/>
<completed v-if="step == 3" :err="err" :status="sub.paymentStatus"/>
</section>

</div>
</template>

<script setup>
import { ref, onMounted } from "vue"
import Dialog from "../dialog.vue"
import Prompt from "./prompt.vue"
import Billing from "./billing.vue"
import Completed from "./completed.vue"

let err = ref("")
const props = defineProps(['user'])
const stripe = Stripe(process.env.STRIPE_KEY)
const step = ref(1)
const token = ref("")

const sub = ref(null)

const clientSecret = new URLSearchParams(window.location.search).get(
  'payment_intent_client_secret'
);

function getCookie(name) {
	var re = new RegExp(name + "=([^;]+)")
	var value = re.exec(document.cookie)

	return (value != null) ? unescape(value[1]) : null
}

function intent(u) {
	return
  
  return fetch(`/api/user/subscribe`,
	    {method: 'POST',
	        body: JSON.stringify(u),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${token.value}`,
    		},
        }).then(resp => {
            if (resp.ok) {
              resp.json().then(s => {
                err.value = ""
                console.log(s)
                sub.value = s
                
                if (["processing", "succeeded"].includes(s.paymentStatus) &&
                clientSecret == s.clientSecret) {
                  step.value = step.value + 2
                } else if (s.paymentStatus == "requires_payment_method") {
                  step.value++
                } else {
                  step.value = 0
                }
              })
            } else {
              resp.text().then( e => err.value = e)
            }
        })
}

onMounted(() => {
	console.log(props.user)
})

</script>

<style scoped>
section {
	max-width: 400px;
	margin: auto;
}

div.modal-prompt .form {
}
</style>
