"use strict"

function validateMe() {}

function validateMeAddSecurityDeposit() {
    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() {
    $('#addSecurityDepositForm').submit(function(evt) {
        if (!validateMeAddSecurityDeposit()) {
            evt.preventDefault();
        }
    });
    document.getElementById('rent_rate').addEventListener('change', function() {
       
        calcExchageValueRent("rate_currency", 'rent_rate', "rent_rate_conversion");
        


    }, false);
    document.getElementById('rent_rate').addEventListener('keyup', function() {
       
        calcExchageValueRent("rate_currency", 'rent_rate', "rent_rate_conversion");
        
      
    }, false);
    document.getElementById('tid').addEventListener('change', function() {
       
        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');
        
        currency_change("rate_currency", "conversion_elem");
    }, 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");
        
       
    }, false);
   
    document.getElementById('set_rate').addEventListener('change', function() {}, false);
    
   
    currency_change("rate_currency", "conversion_elem");
    setCurrencies($("#rate_currency :selected").html());
});

  


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', 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");
    }
}



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, rent_rate_elem, output_elem) {
    let amtt_paid = $("#" + payment_elem).val();
    let total = $(`#${rent_rate_elem}`).val();
    total = total.replace(",", "");
    if (isFinite(amtt_paid) && isFinite(total) && amtt_paid != "" && total != "") {
        amtt_paid = parseFloat(amtt_paid);
        let balance = parseFloat(total - amtt_paid);
        $("#" + output_elem).val(
            parseFloat(balance).toLocaleString('en-EN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            }));

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


}



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["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");
                       
                    } else {
                        window.location.href = '../index.php';
                    }
                }
            });
        } else {
            $("#" + rent_rate_element_id).val("");
        }
    }
    
}

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

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

}





