<template>
<div v-if="downpayment && totalMonthly > 0">

<section class="form inputs">
<h3>Monthly Payment - ${{totalMonthly}}</h3>
<label>Loan payment: ${{loanPayment.toFixed(2)}}</label>
<label v-if="loan.mi.monthly">
    Mortgage insurance: ${{(loan.amount*loan.mi.rate/100/12).toFixed(2)}}
</label>
<label>Property taxes: ${{loan.tax}}</label>
</section>

<section class="form inputs">
<h3>Cash to Close - ${{totalMonthly}}</h3>
<label>Closing costs: ${{fees}}</label>
<label v-if="credits">Credits: ${{credits}}</label>
<label>Down payment: ${{downpayment.toFixed(2)}}</label>
<label v-if="!loan.mi.monthly">
    Mortgage insurance: ${{(loanPayment*loan.mi.rate/100).toFixed(2)}}
</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'
const props = defineProps(['downpayment', 'loan', 'valid', '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
    if (!props.loan.mi.monthly) amount =
    amount + props.loan.mi.rate/100*(amount+props.downpayment)
    return amortize(props.loan.amount,
    props.loan.interest / 100 / 12,
    props.loan.term*12)
})
  
const totalMonthly = computed (
    () => (loanPayment.value +
        props.loan.tax +
        props.loan.hoa +
        props.loan.hazard).toFixed(2)
    )

const totalCash = computed (
    () => (fees.value +
        credits.value +
        props.downpayment).toFixed(2)
    )

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

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

const cashToClose = computed(() => {
    return fees + credits + downpayment
})

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

}

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

</script>