<template>
<div v-if="valid">

<section class="form inputs">
<h3>Monthly Payment - ${{format(totalMonthly)}}</h3>
<label>Loan payment: ${{format(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.hoa)}}</label>
</section>

<section class="form inputs">
<h3>Cash to Close - ${{format(cashToClose)}}</h3>
<label>Closing costs: ${{format(fees)}}</label>
<label v-if="credits">Credits: ${{credits}}</label>
<label>Down payment: ${{format(downpayment)}}</label>
<label v-if="!loan.mi.monthly">
    Mortgage insurance: ${{format(loan.amount*loan.mi.rate/100)}}
</label>
</section>

<section class="form inputs">
<button>Save Estimate</button>
<button>Generate PDF</button>
</section>

</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
let valid = ref(false)
const props = defineProps(['downpayment', 'loan', 'token', 'estimate'])

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

const loanPayment = computed(() => {
    let amount = props.loan.amount
    
    return amortize(props.loan.amount,
    props.loan.interest / 100 / 12,
    props.loan.term*12)
})
  
const totalMonthly = computed (() => {
    let total = loanPayment.value +
        props.loan.tax +
        props.loan.hoa +
        props.loan.hazard
        
    if (props.loan.mi.monthly) {
        total = total + props.loan.mi.rate/100*(props.loan.amount)
    }
    return total
})

// Closing costs
const fees = computed(() => {
    return props.loan.fees.reduce((total, x) => {
            return x.amount > 0 ? total + x.amount : 0
        }, 0
    )
})

const credits = computed(() => {
    return props.loan.fees.reduce((total, x) => {
            return x.amount < 0 ? total + x.amount : 0
        }, 0
    )
})

const cashToClose = computed(() => {
    let total = fees.value + credits.value + props.downpayment
    if (!props.loan.mi.monthly) {
        total = total + props.loan.mi.rate/100*(props.loan.amount)
    }
    
    return total
})

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
		    return
		} else {
		    // resp.text().then(t => this.errors = [t])
		    // window.location.hash = 'new'
	    }
	})

}

// Print number of cents as a nice string of dollars
function format(num) {
    return (num/100).toFixed(2)
}

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

</script>
