<template>
<div v-if="valid && props.loan.result">

<section class="form inputs">
<h3>Monthly Payment - ${{format(loan.result.totalMonthly)}}</h3>
<label>Loan payment: ${{format(loan.result.loanPayment)}}</label>
<label v-if="loan.mi.monthly">
    Mortgage insurance: ${{format(loan.amount*loan.mi.rate/100/12)}}
</label>
<label>Property taxes: ${{format(loan.tax)}}</label>
<label>Homeowner's Insurance: ${{format(loan.hoi)}}</label>
<label v-if="loan.hazard">
    Hazard insurance: ${{format(loan.hazard)}}
</label>
</section>

<section class="form inputs">
<h3>Cash to Close - ${{format(loan.result.cashToClose)}}</h3>
<label>Closing costs: ${{format(loan.result.totalFees)}}</label>
<label v-if="loan.result.totalCredits">
Credits: ${{format(loan.result.totalCredits)}}
</label>
<label>Down payment: ${{format(downpayment)}}</label>
<label v-if="!loan.mi.monthly">
    Mortgage insurance: ${{format(loan.mi.upfront)}}
</label>
</section>

<section class="form inputs">
<button :disabled="saved" @click="create">Save Estimate</button>
<button @click="() => download(props.estimate)">Generate PDF</button>
</section>

<DDialog v-if="dlink" @close="() => dlink = ''"
:fileName="`estimate-${props.estimate.id}.pdf`" :url="dlink">
</DDialog>

</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { format } from '../../helpers.js'
import DDialog from "../download-dialog.vue"

const props = defineProps(['downpayment', 'loan', 'token', 'estimate'])
const emit = defineEmits(['update'])
let valid = ref(false)
let saved = ref(false)
let dlink = ref('')

function amortize(principle, rate, periods) {
    return principle * rate*(1+rate)**periods / ((1+rate)**periods - 1)
}

function validate() {
    fetch(`/api/estimate/validate`,
		{method: 'POST',
		    body: JSON.stringify(props.estimate),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
	}).then(resp => {
		if (resp.ok && resp.status == 200) {
		  valid.value = true
		  summarize()
		}
	})
}

function summarize() {
    fetch(`/api/estimate/summarize`,
		{method: 'POST',
		    body: JSON.stringify(props.estimate),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
	}).then(resp => {
		if (resp.ok && resp.status == 200) return resp.json()
	}).then(e => {
	  emit('update', e)
	})

}

function create() {
    saved.value = true
    fetch(`/api/estimate`,
		{method: 'POST',
		    body: JSON.stringify(props.estimate),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
	}).then(resp => {
		if (resp.ok && resp.status == 200) {
		    saved.value = true
		    return
		} else {
		    resp.text().then(t => console.log(t))
		    saved.value = false
	    }
	})

}

function download(estimate) {
  fetch(`/api/pdf`,
		{method: 'POST',
		    body: JSON.stringify(estimate),
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${props.token}`,
    		},
	}).then(response => {
		if (response.ok) { return response.blob() }
	}).then (result => {
		if (!result) return // Exit if token is invalid or blank file returned
		dlink.value = URL.createObjectURL(result)
	})
}

onMounted(() => {validate()})

</script>
