<template>
<div id="pdf-doc" ref="doc" v-if="estimate">

<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.phone}}</small>
</div>
<img :src="avatar"/>
</div>

</header>

<button @click="makePDF">Generate</button>
</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 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() {
  html2pdf(doc.value)
}


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)
	})
}

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

<style scoped>
header.heading {
    display: flex;
}

.user-info {
    display: flex;
    flex-flow: column;
}
</style>
