<template>
<div id="pdf-doc" ref="doc" v-if="estimate">
<div class="disclaimer"><p>Actual costs may vary from estimates after approval. Get an official quote before choosing a loan.</p></div>

<header class="heading">

<img :src="letterhead" />

<div>

<div class="user-info">
<h4>{{user.firstName + " " + user.lastName}}</h4>
<span>{{user.email}}</span>
<span>{{user.phone}}</span>
<small>{{user.address.street}}</small>
<small>
{{`${user.address.city}, ${user.address.region} ${user.address.zip}`}}
</small>
</div>
<img :src="avatar"/>
</div>

</header>

<button @click="getPdf">Generate</button>
<a :href="pdfLink" v-if="pdfLink" download="estimate.pdf">download </a>
</div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue"
import html2pdf from "html2pdf.js";

const doc = ref(null)
const props = defineProps(['token', 'estimate', 'user'])
const estimate = ref(null)
const estimates = ref(null)
const pdfLink = ref('')

const letterhead = computed(() => {
    if (!props.user.letterhead) return null
  return URL.createObjectURL(props.user.letterhead)
})

const avatar = computed(() => {
    if (!props.user.letterhead) return null
    console.log(props.user)
    return URL.createObjectURL(props.user.avatar)
})

function makePDF() {
    var opt = {
        image: { type: 'png', quality: 1 },
    }

  html2pdf(doc.value, opt)
}


function getEstimates() {
	return fetch(`/api/estimates`,
		{method: 'GET',
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
	}).then(response => {
		if (response.ok) { return response.json() } else {
		    response.text().then(t => console.log(t))
		}
	}).then (result => {
		if (!result || !result.length) return // Exit if token is invalid or no fees are saved
		estimates.value = result
		// console.log(result)
	})
}

function getPdf() {
	fetch(`/api/pdf`,
		{method: 'POST',
		  body: JSON.stringify(estimate.value),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
	}).then(response => {
		if (response.ok) { return response.blob() }
		else {
		    return null
		}
	}).then (result => {
		if (!result) return
		pdfLink.value = URL.createObjectURL(result)
	})
}

onMounted(() => {
    getEstimates().then(() => estimate.value = estimates.value[0])
})
</script>

<style scoped>
#pdf-doc {
    margin: 4px 30px;
}

.disclaimer {
    font-weight: bold;
    border-bottom: 1px solid lightgrey;
    margin-bottom: 20px;
    color: var(--text);
}

.disclaimer p {
    margin: 5px 0;
}

h4 {
    margin: 4px 0;
}

header.heading {
    display: flex;
    justify-content: space-between;
}

.user-info {
    display: flex;
    flex-flow: column;
}

#pdf-doc header.heading > div {
    display: flex;
    gap: 8px;
    text-align: right;
}
</style>
