var count = 0;
var deleted_contact_array = [];
$(document).ready(function() {
    $('#btnAccountSave').on('click', addAccount);
    $('#btnAccountUpdate').on('click', updateAccount);
    $('#btnAccountLogout').on('click', onLogout);
    getAutoSearch("ACCOUNT_NAME_SEARCH");    
    if($('#txtAccountID').val() == 0) $('#btnAccountDelete').css('display', 'none');
}) ;

function addAccount() {
    saveAccount(C_ADD);
}

function updateAccount() {
    saveAccount(C_UPDATE);
}

function getAutoSearch(type) {
    var data = { "type": type, "account_flag": $('#cobAccountFlag').val() };
    var url = "request.pzx?c=" + account_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onAutoSearch, null);
    // $('#divAccountContactDetail').html('');
}

function onAutoSearch(obj, resp) {
    if (resp.status == C_OK) {
        if (resp.data != null && resp.data.length != 0) {
            var filteredAutoSearch = resp.data;
            if (resp.type == "ACCOUNT_NAME_SEARCH") {
                $('#txtAccountName').autocomplete({
                    source: filteredAutoSearch,
                    minLength: 1,
                    autoFocus: true,
                    // select: function(event, ui) {
                    //     $('#txtAccountName').val(ui.item.value);
                    //     changeAccountName();
                    // }
                });
            }
        }
    }
}

function changeAccountName() {
    var data = {
        "type": "GET_ACCOUNT_INFO",
        "account_name" : $('#txtAccountName').val(),
    }
    var url = "request.pzx?c=" + account_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseAccount, null);
}

function saveAccount(type) {
    // if (validateAccount()) {
        var data = {
            "type"      : type,
            
            "id"        : $('#txtAccountID').val(),
            "account_flag" : $('#cobAccountFlag').val(),
            "name"      : $('#txtAccountName').val(),
            "category"  : $('#cobAccountCategory').val(),
            "status"    : $('#cobAccountCompanyStatus').val(),

            "office"    : $('#txtAccountOffice').val(),
            "mobile"    : $('#txtAccountMobile').val(),
            "email"     : $('#txtAccountEmail').val(),
            "address"   : $('#txtAccountAddress').val(),

            "contact"   : getContacts(),
            "deleted_contact" : deleted_contact_array,
        };
        var url = "request.pzx?c=" + account_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseAccount, null);
    // }
}

async function onResponseAccount(obj, resp) {
    if (resp.status != C_OK) {
        swal.fire({
            title: 'Attention',
            text: resp.mesg,
            icon: 'warning',
            fontColor: 'black',
            background: '#f5f3ea',
        });
        return;
    }

    if (resp.status == C_OK) {
        if (resp.type == C_ADD || resp.type == C_UPDATE) {
            swal.fire({
                title: 'Success',
                text: resp.mesg,
                icon: 'success',
                // fontColor: 'black',
                // background: '#f5f3ea',
            });
            clearAccount();
            $('#txtAccountName').val('');
        } else if (resp.type == "GET_ACCOUNT_INFO") {
            clearAccount();
            if (resp.data != "") {
                count = 0;
                $('#btnAccountSave').css('display', 'none');
                $('#btnAccountUpdate').css('display', '');

                $('#cobAccountFlag').val(resp.data.account_flag);
                $('#txtAccountName').val(resp.data.name);
                $('#txtAccountID').val(resp.data.id);
                $('#cobAccountCategory').val(resp.data.category);
                $('#cobAccountCompanyStatus').val(resp.data.status);

                $('#txtAccountOffice').val(resp.data.office);
                $('#txtAccountMobile').val(resp.data.mobile);
                $('#txtAccountEmail').val(resp.data.email);
                $('#txtAccountAddress').val(resp.data.address);
                
                contact_array = resp.data.contact;
                // Use for...of loop instead of forEach for async operations
                for (const contact of contact_array) {
                    await addAccountContact();
                    const currentIndex = count - 1;
                    $('#txtAccountContactName' + currentIndex).val(contact.contact_name);
                    $('#txtAccountContactID' + currentIndex).val(contact.contact_id );
                    $('#txtAccountContactPersonID' + currentIndex).val(contact.person_id);
                    $('#txtAccountContactDesignation' + currentIndex).val(contact.contact_designation);
                    $('#txtAccountContactDepartment' + currentIndex).val(contact.contact_dept);
                    $('#txtAccountContactReportTo' + currentIndex).val(contact.contact_report_to);
                    $('#txtAccountContactPhone' + currentIndex).val(contact.contact_phone);
                    $('#cobAccountPreferContact' + currentIndex).val(contact.contact_prefer);
                    $('#cobAccountPreferContact' + currentIndex).trigger('change');
                    $('#txtAccountContactEmail' + currentIndex).val(contact.contact_email);
                    $('#txtAccountComment' + currentIndex).val(contact.contact_comment);
                }
                $('#btnAccountDelete').css('display', 'inline');
            }
        }
    }
}

function getContacts(){
    var contact_array = [];
    $('#divAccountContactDetail div[id^="divAccountContact"]').each(function() {
        data = {
            "contact_id"          : $(this).find('input[id^="txtAccountContactID"]').val(),
            "contact_person_id"   : $(this).find('input[id^="txtAccountContactPersonID"]').val(),
            "contact_name"        : $(this).find('input[id^="txtAccountContactName"]').val(),
            "contact_designation" : $(this).find('input[id^="txtAccountContactDesignation"]').val(),
            "contact_dept"        : $(this).find('input[id^="txtAccountContactDepartment"]').val(),
            "contact_report_to"   : $(this).find('input[id^="txtAccountContactReportTo"]').val(),
            "contact_email"       : $(this).find('input[id^="txtAccountContactEmail"]').val(),
            "contact_phone"       : $(this).find('input[id^="txtAccountContactPhone"]').val(),
            "contact_prefer"      : $(this).find('select[id^="cobAccountPreferContact"]').val(),
            "contact_comment"     : $(this).find('textarea[id^="txtAccountComment"]').val()
        }
        
        contact_array.push(data);
    });
    return contact_array;
}

// Generic expand/collapse helper — pass the icon selector and the detail selector
function expandCollapse(iconSelector, detailSelector) {
    var $icon = $(iconSelector);
    if ($icon.attr("class") == "fa fa-sort-up") {
        $icon.attr("class", "fa fa-sort-down");
    } else {
        $icon.attr("class", "fa fa-sort-up");
    }
    $(detailSelector).slideToggle(300);
}

function deleteAccountContact(id){
    deleted_contact_array.push(id);
    count--;
    $("#divAccountContact" + id).remove();
}

async function addAccountContact(){
    $('#divAccountContactDetail').append(
        //header
        '<div class="history-card position-relative mb-2" id="divAccountContact' + count + '">' +
            '<div class="history-header d-flex justify-content-between align-items-center" onclick="expandCollapse(\'#expandIcon' + count + '\', \'#collapse_' + count + '\')">' +
                '<a class="text-decoration-none text-dark w-100">' +
                    '<div class="d-flex justify-content-between align-items-center">' +
                        '<strong>Contact</strong>'+
                        '<button style="float:right;" type="button" class="btn btn-danger btn-sm" title="Delete" onclick="deleteAccountContact('+count+')">'+
                            '<i class="fa fa-trash-o" style="font-size:10px;"></i>'+
                        '</button>'+
                    '</div>' +
                '</a>' +
            '</div>' +
            '<div class="mt-2" id="collapse_' + count + '">' +
                '<div class="row g-2 border-top pt-2 form-section">' +
                    '<div class="col-6">' +
                        '<input type="text" class="form-control" id="txtAccountContactName' + count + '" placeholder="Contact Name">' +
                        '<input type="hidden" class="form-control" id="txtAccountContactID' + count + '" value="0">' +
                        '<input type="hidden" class="form-control" id="txtAccountContactPersonID' + count + '" value="0">' +
                    '</div>' +
                    '<div class="col-6">' +
                        '<input type="text" class="form-control" id="txtAccountContactDesignation' + count + '" placeholder="Contact Designation">' +
                    '</div>' +
                    '<div class="col-6">' +
                        '<input type="text" class="form-control" id="txtAccountContactDepartment' + count + '" placeholder="Contact Department">' +
                    '</div>' +
                    '<div class="col-6">' +
                        '<input type="text" class="form-control" id="txtAccountContactReportTo' + count + '" placeholder="Contact Report To">' +
                    '</div>' +
                    '<div class="col-6">' +
                        '<input type="text" class="form-control" id="txtAccountContactPhone' + count + '" placeholder="Contact Phone">' +
                    '</div>' +
                    '<div class="col-6">' +
                        '<select class="form-control" multiple="multiple" id="cobAccountPreferContact' + count + '">' +
                            '<option value="1">Prefer Whatsapp</option>' +
                            '<option value="2">Prefer Telegram</option>' +
                            '<option value="3">Prefer Email</option>' +
                            '<option value="4">Prefer Call</option>' +
                            '<option value="5">Email Promotion</option>' +
                        '</select>' +
                    '</div>' +
                    '<div class="col-12">' +
                        '<input type="text" class="form-control" id="txtAccountContactEmail' + count + '" placeholder="Contact Email">' +
                    '</div>' +
                    '<div class="col-12">' +
                        '<textarea class="form-control" rows="5" id="txtAccountComment' + count + '" placeholder="Comment"></textarea>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>'
    );
    $('#cobAccountPreferContact'+ count).select2({
        placeholder: "Select Pefer Contact", // optional placeholder
        allowClear: true
    });
    count++;
    return;
}

function clearAccount(){
    $('#btnAccountSave').css('display', '');
    $('#btnAccountUpdate').css('display', 'none');

    $('#divAccountContactDetail').html('');
    $('#cobAccountFlag').val('');
    // $('#txtAccountName').val('');
    $('#txtAccountID').val(0);
    $('#cobAccountCategory').val(0);
    $('#cobAccountCompanyStatus').val(0);

    $('#txtAccountOffice').val('');
    $('#txtAccountMobile').val('');
    $('#txtAccountEmail').val('');
    $('#txtAccountAddress').val('');
}