"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 () {
        calcExchageValueRent("rate_currency", 'rent_rate', "rent_rate_conversion");
        computeRentTotalAndBalance();
    }, false);

    document.getElementById('rent_rate').addEventListener('keyup', function () {
        calcExchageValueRent("rate_currency", 'rent_rate', "rent_rate_conversion");
        computeRentTotalAndBalance();
    }, false);

    document.getElementById('tid').addEventListener('change', function () {
        getPreviousRentPeriod('uid', "previousRentReport");
        getAvailableDatesForCurrentMonth('uid', "availableDates");
        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', 'rate_currency');
        getPreviousRentPeriod('uid', "previousRentReport");
        getAvailableDatesForCurrentMonth('uid', "availableDates");
        currency_change("rate_currency", "conversion_elem");
    }, false);

    document.getElementById('duration').addEventListener('change', function () {
        findEndPeriod();
    }, false);

    document.getElementById('period_type').addEventListener('change', function () {
        findEndPeriod();
        computeRentTotalAndBalance();
    }, 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");
        computeRentTotalAndBalance();
    }, false);

    document.getElementById('duration').addEventListener('keyup', function () {
        findEndPeriod();
    }, false);

    initialiseAddRent("tid", "uid", "rent_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();
}

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', rate_currency_elem);
    } else {
        element.removeAttr("disabled");
        rate_currency.removeAttr("disabled");
    }
}

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") { // Yearly
        if (isFinite(period) && isFinite(rent_rate) && period != "" && rent_rate != "") {
            let total = parseFloat(rent_rate) * (period * 12); // Convert years to months
            $("#" + output_element).val(
                parseFloat(total).toLocaleString('en-EN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }));
        } else {
            $("#" + output_element).val("");
        }
    } else if ($("#period_type").val() == "M") { // Monthly
        if (isFinite(period) && isFinite(rent_rate) && period != "" && rent_rate != "") {
            let total = parseFloat(rent_rate) * parseFloat(period);
            $("#" + output_element).val(
                parseFloat(total).toLocaleString('en-EN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }));
        } else {
            $("#" + output_element).val("");
        }
    } else if ($("#period_type").val() == "D") { // Daily
        if (isFinite(period) && isFinite(rent_rate) && period != "" && rent_rate != "") {
            let total = parseFloat(rent_rate) * parseFloat(period);
            $("#" + output_element).val(
                parseFloat(total).toLocaleString('en-EN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }));
        } else {
            $("#" + output_element).val("");
        }
    }
}

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

function getUnitRent(value_element_id, rent_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["d_rate"]); // Set daily rate (d_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("");
        }
    }
}

function calcEndmonthAndEndYear(input_month_element, input_year_element, period_element, output_month_element, output_year_element) {
    let period_type = $("#period_type").val();
    let start_date = new Date($("#" + input_year_element).val(), $("#" + input_month_element).val() - 1, 1);
    let period = parseInt($("#" + period_element).val());

    if (period_type == "Y") {
        start_date.setFullYear(start_date.getFullYear() + period);
    } else if (period_type == "M") {
        start_date.setMonth(start_date.getMonth() + period);
    } else if (period_type == "D") {
        start_date.setDate(start_date.getDate() + period);
    }

    $("#" + output_month_element).val(start_date.getMonth() + 1);
    $("#" + output_year_element).val(start_date.getFullYear());
}
