"use strict"

function validateMe() {}

function validateMeAddRent() {
    let rate_currency_elem_value = $('#rate_currency').val();
    $("#rate_currency_id").val(rate_currency_elem_value.split("-")[0]);                                                                                                          
    $("#rent_rate").removeAttr("disabled");
    $("#rate_currency").removeAttr("disabled");

    return true;
}

$(function() {
    $('#addRentForm').submit(function(evt) {
        if (!validateMeAddRent()) {
            evt.preventDefault();
        }
    });
    document.getElementById('rent_rate').addEventListener('change', function() {
        calcYearlyRent('rent_rate', 'yearly_rate');
        calcExchageValueRent("rate_currency", 'rent_rate', "rent_rate_conversion");
        calcExchageValueRent("rate_currency", 'yearly_rate', "yearly_rate_conversion");


    }, false);
    document.getElementById('rent_rate').addEventListener('keyup', function() {
        calcYearlyRent('rent_rate', 'yearly_rate');
        calcExchageValueRent("rate_currency", 'rent_rate', "rent_rate_conversion");
        calcExchageValueRent("rate_currency", 'yearly_rate', "yearly_rate_conversion");
        computeRentTotalAndBalance();
    }, false);
    document.getElementById('tid').addEventListener('change', function() {
        getPreviousRentPeriod('uid', "previousRentReport");
        reset_currency("rate_currency", $("#" + "default_currency_id").val());
        currency_change("rate_currency", "conversion_elem");

    }, false);

    document.getElementById('uid').addEventListener('change', function() {
        getUnitRent('uid', 'rent_rate', 'yearly_rate', 'rate_currency');
        getPreviousRentPeriod('uid', "previousRentReport");
        currency_change("rate_currency", "conversion_elem");
    }, false);

    document.getElementById('startMonth').addEventListener('change', function() {
        findEndPeriod();
    }, false);
    document.getElementById('startYear').addEventListener('change', function() {
        findEndPeriod();
    }, false);
    document.getElementById('duration').addEventListener('change', function() {
        findEndPeriod();
    }, false);
    document.getElementById('period_type').addEventListener('change', function() {
        findEndPeriod();
    }, false);
    document.getElementById('rate_currency').addEventListener('change', function() {
        setCurrencies($("#rate_currency :selected").html());
        currency_change("rate_currency", "conversion_elem");
        calcExchageValueRent("rate_currency", 'rent_rate', "rent_rate_conversion");
        calcExchageValueRent("rate_currency", 'yearly_rate', "yearly_rate_conversion");
        computeRentTotalAndBalance();
    }, false);
    document.getElementById('duration').addEventListener('keyup', function() {
        findEndPeriod();
    }, false);
    document.getElementById('set_rate').addEventListener('change', function() {}, false);
    initialiseAddRent("tid", "uid", "rent_rate", "yearly_rate", "startMonth", "startYear", "duration", "endMonth", "endYear");
    computeRentTotalAndBalance();
    currency_change("rate_currency", "conversion_elem");
    setCurrencies($("#rate_currency :selected").html());
});

function findEndPeriod() {
    calcEndmonthAndEndYear("startMonth", "startYear", "duration", "endMonth", "endYear");
    computeRentTotalAndBalance();
}
// const checkDefaultCurencySelected = (default_currency_elem, selected_currency_elem) => {
//     return $(`#${default_currency_elem}`).val() === $(`#${selected_currency_elem}`).val().split("-")[0];
// }

function setRateManually(rate_elem, rate_currency_elem) {
    let element = $(`#${rate_elem}`);
    let rate_currency = $(`#${rate_currency_elem}`);
    if (element.attr("disabled") == undefined || rate_currency.attr("disabled") == "") {
        element.attr("disabled", "disabled");
        rate_currency.attr("disabled", "disabled");
        getUnitRent('uid', 'rent_rate', 'yearly_rate', rate_currency_elem);
    } else {
        element.removeAttr("disabled");
        rate_currency.removeAttr("disabled");
    }
}

function currency_change(elem, elem_class) {
    if ($(`#${elem}`).val().split("-")[0] != $("#default_currency_id").val()) {
        $(`.${elem_class}`).show(500, "swing");
    } else {
        $("." + elem_class).hide(500, "swing");
    }
}
/**
 * Foreign Currency Exchange
 */
// function calcExchageValueRent(rate_currency_elem, input_amount_elem, output_amount_elem) {
//     try { // Get rate from selected currency eg $ - 5.900 [symbol - exchange_rate]
//         let currency_details = $("#" + rate_currency_elem).val();
//         let rate = currency_details.split("-")[1];

//         let foreign_amount = $("#" + input_amount_elem).val();
//         rate = parseFloat(rate);
//         foreign_amount = parseFloat(foreign_amount);
//         $("#" + output_amount_elem).val(parseFloat(rate * foreign_amount).toLocaleString('en-EN', {
//             minimumFractionDigits: 2,
//             maximumFractionDigits: 2
//         }));
//     } catch (error) {
//         console.log(error);
//         sweetAlert.fire("Error occured converting currency");
//     }
// }

let setCurrencyExchangeRate = (async(ratesJSON) => {
    let optionsElems = '';
    for (let i = 0; i < ratesJSON.length; i++) {
        optionsElems += `<option value="${ratesJSON[i][0]}">${ratesJSON[i][1]}</option>`
    }
    const { value: formValues } = await Swal.fire({
        title: 'Select Currency',
        html: `<select class="mySelect swal2-select" id="swal-currency_id" 
        onchange="get_currency_exchange_rate('swal-currency_id', 'swal-exchange-rate')" required="" placeholder="Select Month">
        ${optionsElems}
        </select><input id="swal-exchange-rate" class="swal2-input">`,
        focusConfirm: false,
        confirmButtonText: '<i class="fa fa-floppy-o"></i> Change',
        didRender: () => {
            let selected_currency_id = document.getElementById("rate_currency").value;
            let testInp = document.getElementById("swal-currency_id").value = selected_currency_id.split("-")[0];
            get_currency_exchange_rate('swal-currency_id', 'swal-exchange-rate');
        },
        preConfirm: () => {
            return { id: document.getElementById('swal-currency_id').value, rate: document.getElementById('swal-exchange-rate').value }
        }
    })

    if (formValues) {
        const r = await set_currency_exchange_rate(formValues["id"], formValues["rate"]);
        let selectedOption = document.getElementById("rate_currency").value.split("-")[0];
        updateCurrencyOptions("rate_currency");
        setTimeout(function() {
            let options = document.getElementById("rate_currency").options;
            for (let i = 0; i < options.length; i++) {
                let value = options[i].value;
                if (value.split("-")[0] == selectedOption) {
                    $("#rate_currency").val(value);
                    break;
                }
            }
            calcExchageValueRent("rate_currency", 'rent_rate', "rent_rate_conversion");
            calcExchageValueRent("rate_currency", 'yearly_rate', "yearly_rate_conversion");
            computeRentTotalAndBalance();
        }, 500);
    }
});

function get_currency_exchange_rate(input_elem, output_elem) {
    let cid = document.getElementById(input_elem).value;
    $.ajax({
        url: '../ajax/currency.php',
        type: 'POST',
        data: '&cid=' + cid.toString() + '&token=getRate',
        dataType: 'html',
        success: function(data) {
            console.log(data);
            try {
                let result = JSON.parse(data);
                $("#" + output_elem).val(result["rate"]);
            } catch (error) {
                sweetError("Problem occured while getting exchange rate");
                console.log(error);
            }
        }
    });
}

async function set_currency_exchange_rate(id, rate) {
    $.ajax({
        url: '../ajax/currency.php',
        type: 'POST',
        async: false,
        data: '&cid=' + id + "&rate=" + rate + '&token=setRate',
        dataType: 'html',
        success: function(data) {
            const res = JSON.parse(data);
            console.log(res);
            return res;
        },

    });
}

function updateCurrencyOptions(rent_rate_currency_elem_id) {
    $.ajax({
        url: '../ajax/currency.php',
        type: 'POST',
        data: '&token=getCurrencyOptions',
        dataType: 'html',
        success: function(data) {
            document.getElementById(rent_rate_currency_elem_id).innerHTML = data;
        },
    });
}
const reset_currency = (rate_currency_elem_id, cid) => {
    let options = document.getElementById(rate_currency_elem_id)
    for (let i = 0; i < options.length; i++) {
        let value = options[i].value;
        if (value.split("-")[0] == cid) {
            $("#" + rate_currency_elem_id).val(value);
            break;
        }
    }
};

function sweetError(errorMsg) {
    Swal.fire({ icon: 'error', title: 'Oops...', text: errorMsg })
}


function calcBalance(payment_elem, total_rent_elem, output_elem) {
    let amt_paid = $("#" + payment_elem).val();
    let total = $(`#${total_rent_elem}`).val();
    total = total.replace(",", "");
    if (isFinite(amt_paid) && isFinite(total) && amt_paid != "" && total != "") {
        amt_paid = parseFloat(amt_paid);
        let balance = parseFloat(total - amt_paid);
        $("#" + output_elem).val(
            parseFloat(balance).toLocaleString('en-EN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            }));

    } else {
        $("#" + output_elem).val("N/A");
    }


}

function calcTotalRent(period_element, rent_rate_element, output_element) {
    let period = $("#" + period_element).val();
    let rent_rate = $("#" + rent_rate_element).val();
    period = period.replace(",", "");
    rent_rate = rent_rate.replace(",", "");
    if ($("#period_type").val() == "Y") {
        if (isFinite(period) && isFinite(rent_rate) && period != "" && rent_rate != "") {
            rent_rate = parseFloat(rent_rate);
            period *= 12;
            let total = parseFloat(rent_rate * period);
            $("#" + output_element).val(
                parseFloat(total).toLocaleString('en-EN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }));

        } else {
            $("#" + output_element).val("");
        }
    } else if ($("#period_type").val() == "M") {
        if (isFinite(period) && isFinite(rent_rate) && period != "" && rent_rate != "") {
            rent_rate = parseFloat(rent_rate);
            let total = parseFloat(rent_rate * period);
            $("#" + output_element).val(
                parseFloat(total).toLocaleString('en-EN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }));

        } else {
            $("#" + output_element).val("");
        }
    }
}

function initGetTenantUnit(value_element_id, return_element_id, rate_rate_elem) {
    if (typeof value_element_id !== "undefined" && typeof return_element_id !== "undefined" && typeof rate_rate_elem !== "undefined" && typeof return_yearly !== "undefined") {
        let tid = $("#" + value_element_id).val();
        if (tid != '') {
            $.ajax({
                url: '../ajax/getunit.php',
                type: 'POST',
                data: '&tid=' + tid + '&token=get_tenant_unit',
                dataType: 'html',
                success: function(data) {
                    if (data != '-99') {
                        $("#" + return_element_id).html(data);
                        if ($("#uid_edit").val() != "")
                            $("#" + return_element_id).val($("#uid_edit").val());
                        setTimeout(function() {
                            getUnitRent(return_element_id, rate_rate_elem, return_yearly);
                        }, 100);
                    } else {
                        window.location.href = '../index.php';
                    }
                }
            });
        } else {
            let placeholder = '<option value="">--Select Tenant First--</option>';
            $("#" + return_element_id).html(placeholder);
            setTimeout(function() {
                getUnitRent(return_element_id, rate_rate_elem);
            }, 100);
        }
    }
}

function getUnitRent(value_element_id, rent_rate_element_id, yearly_rate_element_id, rate_currency_elem_id) {
    if (typeof value_element_id !== "undefined" && typeof rent_rate_element_id !== "undefined") {
        let uid = $("#" + value_element_id).val();
        if (uid != '') {
            $.ajax({
                url: '../ajax/getunit.php',
                type: 'POST',
                data: '&uid=' + uid + '&token=getUnitRent',
                dataType: 'html',
                success: function(data) {
                    if (data != '-99') {
                        let result = JSON.parse(data);
                        $("#" + rent_rate_element_id).val(result["m_rate"]);

                        let options = document.getElementById(rate_currency_elem_id)
                        for (let i = 0; i < options.length; i++) {
                            let value = options[i].value;
                            if (value.split("-")[0] == result["rate_currency_id"]) {
                                $("#" + rate_currency_elem_id).val(value);
                                break;
                            }
                        }
                        setCurrencies(result["rate_currency"]);
                        currency_change("rate_currency", "conversion_elem");
                        calcExchageValueRent("rate_currency", rent_rate_element_id, "rent_rate_conversion");
                        computeRentTotalAndBalance();
                    } else {
                        window.location.href = '../index.php';
                    }
                }
            });
        } else {
            $("#" + rent_rate_element_id).val("");
        }
    }
    if (typeof calcYearlyRent === "function" && typeof yearly_rate_element_id !== "undefined") {
        setTimeout(function() {
            calcYearlyRent(rent_rate_element_id, yearly_rate_element_id);
            calcExchageValueRent("rate_currency", yearly_rate_element_id, "yearly_rate_conversion");
            computeRentTotalAndBalance();
        }, 100);
    }
}

function setCurrencies(currency_symbol) {
    $(".currency").each(function() {
        $(this).html(currency_symbol);
    });
}

function calcYearlyRent(input_element, output_element) {
    let rate = $("#" + input_element).val();
    rate = rate.replace(",", "");
    rate = parseFloat(rate);
    if (rate != "" && Number.isFinite(rate)) {
        let YearlyRate = parseFloat(rate) * 12;
        $("#" + output_element).val(YearlyRate.toFixed(2));
    } else {
        $(`#${output_element}`).val("");
    }
}

function calcEndmonthAndEndYear(input_month_element, input_year_element, period_element, output_month_element, output_year_element) {
    if (typeof input_month_element !== undefined && typeof input_year_element !== undefined && typeof period_element !== undefined && typeof output_month_element !== undefined && typeof output_year_element !== undefined) {
        let startMonth = parseInt($("#" + input_month_element).val());
        let startYear = parseInt($("#" + input_year_element).val());
        let period = parseInt($("#" + period_element).val());
        if ($("#period_type").val() == "Y") {
            if (Number.isInteger(startMonth) && Number.isInteger(startYear) && Number.isInteger(period)) {
                let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
                let after_period = new Date(startYear + period, startMonth - 2, 1);
                $("#" + output_month_element + "1").val(months[after_period.getMonth()]);
                $("#" + output_month_element).val(after_period.getMonth() + 1);
                $("#" + output_year_element).val(after_period.getFullYear());
            } else {
                $("#" + output_month_element).val("N/A");
                $("#" + output_year_element).val("N/A");
            }
        } else if ($("#period_type").val() == "M") {
            if (Number.isInteger(startMonth) && Number.isInteger(startYear) && Number.isInteger(period)) {
                let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
                let after_period = new Date(startYear, startMonth - 2 + period, 1);
                $("#" + output_month_element + "1").val(months[after_period.getMonth()]);
                $("#" + output_month_element).val(after_period.getMonth() + 1);
                $("#" + output_year_element).val(after_period.getFullYear());
            } else {
                $(`#${output_month_element}`).val("N/A");
                $("#" + output_year_element).val("N/A");
            }
        }

    } else {
        console.log("Bad call to function");
    }

}
computeRentTotalAndBalance();


function initialiseAddRent(tenant_id_element, unit_id_element, rent_rate_element, yearly_rate_elemnet, startMonth_element, startYear_element, duration_element, endMonth_element, endYear_element) {
    initGetTenantUnit(tenant_id_element, unit_id_element, rent_rate_element, yearly_rate_elemnet);
    calcEndmonthAndEndYear(startMonth_element, startYear_element, duration_element, endMonth_element, endYear_element);
}

function computeRentTotalAndBalance() {
    calcTotalRent("duration", "rent_rate", "total_amount");
   calcBalance('amt_paid', 'total_amount', 'balance');
}
