<template>
<div v-if="cards && cards.length > 0">
<div class="saved-cards-heading">
<h5>Card</h5> <h5>Default</h5> <h5>Delete</h5>
</div>
<div v-for="card in cards" :key="card.id" class="saved-card">
	<span>{{card.card.brand[0].toUpperCase() + card.card.brand.substring(1)}}
	(••••{{card.card.last4}})</span> 
	<span><input :checked="card.id == preferred" :value="card.id" name="selected-card" type="radio"
	@change="change(card.id)"></span>
	<span><img @click="remove(card.id)" src="../../images/close-icon-black.svg"/></span>
</div>
<p id="billing-error"></p>
</div>
</template>

<script>
function get() {
	fetch('/panel/cards', {
		method: 'GET',
		headers: {'Content-Type': 'application/json',
			'Accept': 'application/json',
		'X-XSRF-TOKEN': this.token}
	}).then((response) => {response.json().then(data => {
		this.cards = data.data
	})})
}

function change(card) {
	fetch('/panel/change-card', {
		method: 'POST',
		headers: {'Content-Type': 'application/json',
			'Accept': 'application/json',
		'X-XSRF-TOKEN': this.token},
		body: JSON.stringify({'card': card})
	}).then((response) => {
		if (response.ok) {
			response.json().then((data) => {
				this.cards = data.data
			})
		} else {
			console.log('bad')
			document.getElementById("billing-error").textContent =
			`${response.status}: ${response.statusText}`
		}
	})
}

function remove(card) {
	if (card.length == 1) {
		return
	}

	fetch('/panel/delete-card', {
		method: 'POST',
		headers: {'Content-Type': 'application/json',
			'Accept': 'application/json',
		'X-XSRF-TOKEN': this.token},
		body: JSON.stringify({'card': card})
	}).then((response) => {
		if (response.ok) {
			response.json().then((data) => {
				this.cards = data.data
			})
		} else {
			document.getElementById("billing-error").textContent =
			`${response.status}: ${response.statusText}`
		}
	})
}

export default {
	data() {
		return {cards: null}
	},
	methods: {get, change, remove},
	created() {
		this.get()
	},
	props: ['token', 'preferred'],
}
</script>