// Current state
window.currentPageNo = 1;
window.currentPageSize = 10;
window.filterParams = {
    id: 0,
    quote_id: 0,
    provider_booking_ref: '',
    // details: '',
    message: '',
    status: '',
    member_id: '',
    cost: '',
    created: '',
    updated: '',
    completed: ''
};

$('#filter-form').submit(e => {
    e.preventDefault();

    const inputs = $('#filter-form input, #filter-form select');

    inputs.each(function() {
        filterParams[this.name] = $(this).val();
    });

    // Set pageNo back to 1 when filter blogs
    currentPageNo = 1;

    loadPage(filterParams);
})

function loadPage(params = null) {
    $('#booking-table').hide();
    $('#booking-table-loading').show();

    const data = {
        pageNo: currentPageNo,
        pageSize: currentPageSize
    };

    if(params) {
        data.params = params;
    }

    $.ajax({
        method: 'post',
        url: '/booking/getReports',
        dataType: 'json',
        data: data,

        success: function(res) {
            $('#booking-table').show();
            $('#booking-table-loading').hide();

            if (res.result.length === 0 && res.pageNo > 0) {
                currentPageNo--;
                return loadPage(filterParams);
            }

            renderBookingTable(res.result);
            renderPagination(res.total, res.pageSize, res.pageNo + 1);
        },
        
        error: function(err) {
            $('#booking-table').show();
            $('#booking-table-loading').hide();

            alertErr(err.responseJSON.errors);
        }
    });
}

function renderBookingTable(result) {
    $('#booking-table tbody').empty();

    if (result.length === 0) {
        const tr = '<tr><td>No result</td><td>No result</td><td>No result</td><td>No result</td><td>No result</td><td>No result</td><td>No result</td><td>No result</td><td>No result</td><td>No result</td><td>No result</td></tr>';
        $('#booking-table tbody').append(tr);
        return;
    }

    for (index in result) {
        var id = result[index].id;
        var quote_id = result[index].quote_id;
        var provider_booking_ref = result[index].provider_booking_ref;
        var details = result[index].details;
        var created = result[index].created;
        var updated = result[index].updated;
        var completed = result[index].completed;
        var status = result[index].status;
        var message = result[index].message;
        var member_id = result[index].member_id;
        var cost = result[index].cost;

        var tr = '<tr>';
        tr += `<td>${id}</td>`;
        tr += `<td>${quote_id}</td>`;
        tr += `<td>${provider_booking_ref}</td>`;
        tr += `<td>${formatJSON(details)}</td>`;
        tr += `<td>${created}</td>`;
        tr += `<td>${updated}</td>`;
        tr += `<td>${completed}</td>`;
        tr += `<td>${status}</td>`;
        tr += `<td>${message}</td>`;
        tr += `<td>${member_id}</td>`;
        tr += `<td>${cost}</td>`;
        tr += '</tr>';

        $('#booking-table tbody').append(tr);
    }
}

function renderPagination(total, pageSize, pageNo = 1) {
    $('#booking-pagination').unbind('page');
    $('#booking-pagination').empty();
    $('#booking-pagination').bootpag({
        total: Math.ceil(total / pageSize),
        page: pageNo,
        maxVisible: 5,
        leaps: true,
        firstLastUse: true,
        first: '←',
        last: '→',
        wrapClass: 'pagination',
        activeClass: 'active',
        disabledClass: 'disabled',
        nextClass: 'next',
        prevClass: 'prev',
        lastClass: 'last',
        firstClass: 'first'
    }).on('page', function(event, pageNo) {
        // Save current state for loadPage function
        currentPageNo = pageNo;
        currentPageSize = pageSize;

        loadPage(filterParams);
    });
}

// Format JSON string from backend so that we can read it easier
function formatJSON(jsonStr) {
    let data = JSON.parse(jsonStr);

    let formatedStr = Object.keys(data).map(key => {
        // Check value of object is an object
        if(typeof data[key] === 'object') {
            return Object.keys(data[key]).map(subKey => {
                return subKey + ': ' + data[key][subKey];
            }).join(', ');
        }

        return key + ': ' + data[key];
    }).join(', ');

    return formatedStr;
}

function alertErr(err) {
    const errors = Object.values(err);
    let message = '';
    
    for (index in errors) {
        message += errors[index] + ' ';
    }

    alert(message);
}