<template>
<div>

<section class="form inputs">
<h3>Monthly Payment - ${{totalMonthly}}</h3>
<label>Loan payment: ${{loanPayment.toFixed(2)}}</label>
<label v-if="loan.mi.monthly">
    Mortgage insurance: ${{(loanPayment*loan.mi.rate/100).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>Credits: ${{credits}}</label>
<label>Downpayment: ${{downpayment.toFixed(2)}}</label>
<label v-if="!loan.mi.monthly">
    Mortgage insurance: ${{(loanPayment*loan.mi.rate).toFixed(2)}}
</label>
</section>

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

</div>
</template>

<script setup>
import { ref, computed } from 'vue'
const props = defineProps(['downpayment', 'loan'])

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

const loanPayment = computed(() => 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)
    )

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