const STATUSES = {
    "Not Started": {
        icon: 'fa-shopping-bag',
        action: 'start',
        buttonText: 'Start Order',
        buttonClass: '',
        cardClass: '',
        nextStatus: 'Started'
    },
    "Started": {
        icon: 'fa-utensils',
        action: 'ready',
        buttonText: 'Mark as Ready',
        buttonClass: '',
        cardClass: '',
        nextStatus: 'Ready'
    },
    "Ready": {
        icon: 'fa-check',
        action: '-',
        buttonText: '-',
        buttonClass: '',
        cardClass: '',
        nextStatus: '-'
    }
}

function fetchOrders(){
    $.ajax({
        type: "POST",
        url: "./includes/order_monitor.php?action=getRec&dest=getData4OrderMonitor",
        cache: false,
        success: function(result) {
            populateOrderMonitorUI(JSON.parse(result));
        },
    });
}

fetchOrders();
window.setInterval(function(){
    fetchOrders();
}, 10000)

var oldNotRedyHtml = '';
var oldReadyHtml = '';
function populateOrderMonitorUI(orders){
    if(Object.keys(orders).length > 0){
        var isNotReadyFirstItem = true;
        var notReadyOrderLeftHtml = '';
        var notReadyOrderRightHtml = '';

        var isReadyFirstItem = true;
        var readyOrderLeftHtml = '';
        var readyOrderRightHtml = '';

        Object.keys(orders).forEach(function(orderId, index){
            const orderItems = orders[orderId];
            const order = orderItems[0];
            const isFirstItem = (isNotReadyFirstItem && order.prepareStatus.toLowerCase() !== 'ready') || (isReadyFirstItem && order.prepareStatus.toLowerCase() === 'ready');
            const orderDateTime = new Date(order.addedDate);
            const orderTime = `${orderDateTime.getHours()}:${orderDateTime.getMinutes()}`;
            var itemsHtml = orderItems.map(function(item){
                return `<li style="display: flex; justify-content: space-between">
                            <div>
                                <div>${item.itemName}</div>
                                <div style="color: #da0a0a">${item.notes ? `<i class="fas fa-comment-alt"></i> ${item.notes}` : ''}</div>
                            </div>
                            <div>x ${item.quantity}</div>
                        </li>`;
            });
            var orderHtml = `
            <div class="order-card ${order.isLate === false ? 'style-two' : ''}" style="${isFirstItem ? 'height: 100%' : ''}">
                <div class="order-card__top">
                    <span class="base-num ${order.prepareStatus.toLowerCase() === 'ready' ? 'order-card-bg-gray' : ''}">${order.orderID}</span>
                    <div class="content-right">
                        <h5 class="order-card__time">${orderTime}</h5>
                        <span class="order-shoping-bag"><i class="fas ${STATUSES[order.prepareStatus]?.icon}"></i></span>
                        <span class="expand-icon" onclick="toggleFullscreen(this)"><i
                                    class="fas fa-expand-alt"></i></span>
                    </div>
                </div>
                <div class="order-card__body ${isFirstItem ? 'style-two' : ''}">
                    <ul class="order-card__content">
                        ${itemsHtml.join('')}
                    </ul>
                </div>
                <div class="${isFirstItem ? 'order-footer-btn-wrapper' : ''} order-card__btn">
                    ${
                        order.prepareStatus.toLowerCase() === 'ready'
                        ? `<span class="order-text-btn late">${order.isLate ? 'Late' : 'Made on time'}</span>`
                        : `<a class="order-card-btn  ${STATUSES[order.prepareStatus]?.buttonClass}"
                                href="javascript:void(0)"
                                id="order_btn_${order.orderID}"
                                onclick="changeOrderStatus(${order.orderID},'${STATUSES[order.prepareStatus]?.nextStatus}')">
                                ${STATUSES[order.prepareStatus]?.buttonText}
                            </a>`
                    }
                </div>
            </div>
            `;

            if(order.prepareStatus.toLowerCase() === 'ready'){
                if(isReadyFirstItem){
                    readyOrderLeftHtml = orderHtml;
                    isReadyFirstItem = false;
                }else{
                    orderHtml = `<div class="order-card-outer">${orderHtml}</div>`;
                    readyOrderRightHtml += orderHtml;
                }
            }else{

                if(isNotReadyFirstItem){
                    notReadyOrderLeftHtml = orderHtml;
                    isNotReadyFirstItem = false;
                }else{
                    orderHtml = `<div class="order-card-outer">${orderHtml}</div>`;
                    notReadyOrderRightHtml += orderHtml;
                }
            }
        });

        // Merged and check dom changed to prevend unusual rendering
        const mergedNotReadyHtml = notReadyOrderLeftHtml + notReadyOrderRightHtml;
        const mergedReadyHtml = readyOrderLeftHtml + readyOrderRightHtml;
        if(mergedNotReadyHtml){
            if(mergedNotReadyHtml !== oldNotRedyHtml){
                $('#not_ready_order_left').html(notReadyOrderLeftHtml);
                $('#not_ready_order_right').html(notReadyOrderRightHtml);
            }
        }else{
            $('#not_ready_order_left').html(notReadyOrderLeftHtml);
            $('#not_ready_order_right').html('<div class="no-order">No pending order</div>');
        }

        if(mergedReadyHtml){
            if( mergedReadyHtml !== oldReadyHtml){
                $('#ready_order_left').html(readyOrderLeftHtml);
                $('#ready_order_right').html(readyOrderRightHtml);
            }
        }else{
            $('#ready_order_left').html('');
            $('#ready_order_right').html('<div class="no-order">No ready order</div>');
        }
        oldNotRedyHtml = mergedNotReadyHtml;
        oldReadyHtml = mergedReadyHtml;
    }
}

function changeOrderStatus(orderID, toStatus){
    var orderBtn = $(`#order_btn_${orderID}`);
    orderBtn.html('Updating...');
    orderBtn.attr('disabled', true);
    $.ajax({
        type: "POST",
        url: "./includes/order_monitor.php?action=updateRec&dest=updateOrderStatus",
        data: {
            orderID,
            toStatus
        },
        cache: false,
        success: function(result) {
            if(result != '1'){
                alert('Failed to update status. Please refresh the page and try again.');
            }
            fetchOrders();
        },
    });
}