<template>
<section class="shadowbox">
<h2>Register</h2>
<account v-if="step == 1" :err="err" @submit="create" />
<billing v-if="step == 2 && !trial" :err="err" :sub="sub"/>
<completed v-if="step == 3" :err="err" :status="sub.paymentStatus"/>
</section>
</template>

<script setup>
import { ref, onMounted } from "vue"
import Account from "./account.vue"
import Billing from "./billing.vue"
import Completed from "./completed.vue"

let err = ref("")
const stripe = Stripe(process.env.STRIPE_KEY)
const step = ref(1)
const token = ref("")
const user = ref(null)
const sub = ref(null)
const trial = ref(false)

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 getUser() {
	token.value = getCookie("skouter")

	return fetch(`/api/user`,
		{method: 'GET',
		headers: {
			"Accept": "application/json",
			"Authorization": `Bearer ${token.value}`,
    		},
	}).then(response => {
		if (response.ok) {
			return response.json()
		}
	})
}

function create(user) {
  console.log(user)
  
  fetch(`/api/user`,
	    {method: 'POST',
	        body: JSON.stringify(user),
    		headers: {
        	"Accept": "application/json",
    		},
        }).then(resp => {
            if (resp.ok) {
              return resp.json().then(u => { err.value = "" }).
              then( () => {
                token.value = getCookie("skouter")
                intent(user)
              } )
            } else {
              resp.text().then( e => err.value = e)
            }
        })
}

function intent(u) {
  let path = `/api/user/subscribe`
  
  if (trial.value) {
    path = `/api/user/trial`
  }
  
  return fetch(path,
	    {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(() => {
  if (window.location.pathname == "/free-trial") {
    trial.value = true
  }
  
  getUser().then( u => {
    if (u) { user.value = u; intent(u) }
  })
})
</script>

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