<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.hoi)}}</label>
<label v-if="loan.hazard">
    Hazard insurance: ${{format(loan.hazard)}}
</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 :disabled="saved" @click="create">Save Estimate</button>
<button>Generate PDF</button>
</section>

</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { format } from '../../helpers.js'
let valid = ref(false)
let saved = 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(() => {    
    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.hoi +
        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'
	    }
	})

}

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 => this.errors = [t])
		    // window.location.hash = 'new'
		    resp.text().then(t => console.log(t))
		    saved.value = false
	    }
	})

}

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

</script>