
function safeJsonParse(str) {
    try {
        return JSON.parse(str);
    } catch (e) {
        return [];
    }
}

function formatPrice(num) {
    if (num === '-' || num === 0) return num;
    return Number(num).toLocaleString('fa-IR');
}

function GetPPType(type) {
    switch (type){
        case "object":
            return "کالای فیزیکی";
        case "duty":
            return "خدمت";
        case "virtual":
            return "محصول مجازی";
    }
    return type;
}

function buildVariableName(list, varIdsString) {
    if (!varIdsString) return '';
    const ids = varIdsString.split(',');
    let names = list
        .filter(v => ids.includes(String(v.id)))
        .map(v => v.text);
    return names.join(' - ');
}

function buildVariableList(list, varIdsString) {
    if (!varIdsString) return null;
    const ids = varIdsString.split(',');
    return list.filter(v => ids.includes(String(v.id)));
}

function gainMOSMainInputFocus() {
    setTimeout(function () {
        $('#manual-order-submit-product-main-input').focus().select();
    }, 500);
}

function buildManualOrderCartItem(fullData, variable, variablesList) {
    return {
        product_id: fullData.id,
        product_image: fullData.image,
        product_name: fullData.text,
        variable_id: variable.id,
        variables: variable.variables,
        variable_name: buildVariableName(variablesList, variable.variables),
        variable_detail_list: buildVariableList(variablesList, variable.variables),
        quantity: 1,
        max_quantity: parseInt(variable.quantity),
        max_quantity_for_user: fullData.pp_quantity_limit_for_every_user,
        is_amazing_discount: fullData.pp_is_amazing_discount,
        amazing_discount_deadline: fullData.pp_is_amazing_discount == 2 ? fullData.pp_amazing_discount_deadline : "",
        type: fullData.pp_type,
        price: variable.price,
        price_off: variable.price_off
    };
}

function pushToFinalCart(item) {

    let current = $('#final_cart_data').val();

    if (!current) current = "[]";

    let cartArray = safeJsonParse(current);

    let existingItem = cartArray.find(i =>
        i.product_id == item.product_id &&
        i.variable_id == item.variable_id
    );

    if (existingItem) {
        // Product already in cart → increase quantity
        let newQuantity = Number(existingItem.quantity) + 1;
        if(existingItem.max_quantity != -200){
            if(existingItem.max_quantity < newQuantity){
                notyf.error('تعداد بیشتری از این محصول موجود نیست');
                return;
            }
        }
        existingItem.quantity = newQuantity;
    } else {
        // New product → add to cart
        item.quantity = 1;
        cartArray.push(item);
    }

    $('#final_cart_data').val(
        JSON.stringify(cartArray, null, 2)
    );

    renderCartTable();

}

function renderCartTable() {

    const $table = $('.manual-order-live-table');
    const $total = $('#cart-total-val');

    const final_cart_data_string = $('#final_cart_data').val();
    const final_cart_data = JSON.parse(final_cart_data_string);

    // Remove old rows (keep header)
    $table.find('tr:not(:first)').remove();

    let total = 0;

    final_cart_data.forEach(item => {

        let finalPrice = (item.price_off && item.price_off > 0)
            ? item.price_off
            : item.price;

        let rowTotal = finalPrice * item.quantity;
        total += rowTotal;

        let image = '';
        if(item.product_image != '') image = '<img class="molt-img" src="'+item.product_image+'">';
        
        let row = `
            <tr>
                <td>${item.product_id}</td>
                <td>${image}</td>
                <td>${item.product_name}</td>
                <td>${item.variable_id}</td>
                <td>${item.variable_name}</td>
                <td class="molt-q">${item.quantity}</td>
                <td>${GetPPType(item.type)}</td>
                <td class="molt-p">${formatPrice(item.price)}</td>
                <td class="molt-po">${item.price_off > 0 ? formatPrice(item.price_off) : ''}</td>
                <td><span data-pp-id="${item.product_id}" data-pp-var-id="${item.variable_id}" class="pp-delete-manual-order-item btn-danger-light edit-small-btn2"><i class="ph ph-trash"></i></span></td>
            </tr>
        `;

        $table.append(row);
    });

    $total.text(formatPrice(total));

    gainMOSMainInputFocus();

}

function openSelectVaribleOptionForManualOrderSubmit(fullData,variablesMap,variablesList){
    // Multiple variables → show selection dialog
    let html = '<div class="swal-variables mos-swal-vars-wrapper">';

    html += '<div class="mos-swal-p-title">'+fullData.text+'</div>';
    variablesMap.forEach((variable, index) => {
        const varName = buildVariableName(variablesList, variable.variables);
        let price = variable.price;
        if(variable.price_off > 0) price = variable.price_off;
        let out_of_stock = "";
        if (variable.status == "out_of_stock") out_of_stock = '<span class="sv-mos-out-of-stock">ناموجود</span>';
        html += `
            <div class="swal-variable-item" data-index="${index}">
                <strong>${varName}</strong> - ${formatPrice(price)} <span>تومان</span>
                ${out_of_stock}
            </div>
        `;
    });

    html += '</div>';

    Swal.fire({
        title: 'انتخاب متغیر محصول',
        html: html,
        showConfirmButton: false,
        showCloseButton: false,
        focusConfirm: false,
        onOpen: () => {
            // attach click event to items
            document.querySelectorAll('.swal-variable-item').forEach(el => {
                el.addEventListener('click', function() {
                    const idx = parseInt(this.dataset.index);
                    const variable = variablesMap[idx];
                    if(variable.status == "out_of_stock"){
                        notyf.error('محصول ناموجود است');
                        return;
                    }
                    let cartItem = buildManualOrderCartItem(fullData, variable, variablesList);
                    pushToFinalCart(cartItem);
                    Swal.close();
                });
            });
        }
    });
}

$(function () { // start of document ready:

    gainMOSMainInputFocus();

    $('#manual-order-submit-product-main-form').on('submit', function(e) {
        e.preventDefault();
        let mainInput = $('#manual-order-submit-product-main-input');
        var searchValue = mainInput.val();
        mainInput.val("");
        //console.log(searchValue); // your logic here

        const $select = $('#manual-order-submit-product-selector');
        // Open select2 and trigger search
        $select.select2('open');
        setTimeout(() => {
            $('.select2-search__field').val(searchValue).trigger('input');
        }, 500);
    });

    $('#manual-order-submit-product-selector').on('select2:open', function () {

        const observer = new MutationObserver(function() {
            let results = $('.select2-results__option:not(.select2-results__message)');
            if (results.length === 1) {
                let result = results.first();
                result.trigger('mouseup'); // auto select
                observer.disconnect();
            }
        });
        observer.observe(document.querySelector('.select2-results'), {
            childList: true,
            subtree: true
        });

    });

    $('#manual-order-submit-product-selector').on('select2:select', function (e) {
        // Full object returned from your API
        const fullData = e.params.data;

        $('#manual-order-submit-product-selector').val(null).trigger('change');

        //console.log("fullData: " + fullData);
        // Save as JSON in textarea
        $('#temp_product_json').val(JSON.stringify(fullData, null, 2));

        let variablesMap  = safeJsonParse(fullData.pp_variables_map);
        let variablesList = safeJsonParse(fullData.pp_variables_list);

        // must have variables
        if (!variablesMap.length) {
            let text = "محصول " + fullData.text + " فاقد متغییر است";
            Swal.fire({
                position: 'center',
                icon: 'error',
                title: text,
                showConfirmButton: true
            });
            gainMOSMainInputFocus();
            return;
        }

        // Auto-pick if only 1 variable
        if (variablesMap.length === 1) { //single variable product

            const variable = variablesMap[0];
            if(variable.status == "out_of_stock"){
                let text = "محصول " + fullData.text + " ناموجود است";
                Swal.fire({
                    position: 'center',
                    icon: 'error',
                    title: text,
                    showConfirmButton: true
                });
                gainMOSMainInputFocus();
                return;
            }
            let cartItem = buildManualOrderCartItem(fullData, variable, variablesList);
            pushToFinalCart(cartItem);

        }else{ //mutiple variable product

            openSelectVaribleOptionForManualOrderSubmit(fullData,variablesMap,variablesList);

        }

    });

    $(document).on('click', '.pp-delete-manual-order-item', function () {

        let product_id  = $(this).data('pp-id');
        let variable_id = $(this).data('pp-var-id');

        let final_cart_data_string = $('#final_cart_data').val();
        let final_cart_data = JSON.parse(final_cart_data_string);

        // Remove item from final_cart_data
        final_cart_data = final_cart_data.filter(item => {
            return !(
                item.product_id == product_id &&
                item.variable_id == variable_id
            );
        });

        $('#final_cart_data').val(
            JSON.stringify(final_cart_data, null, 2)
        );

        // Refresh UI
        renderCartTable();
    });


    $("#manual-order-submit-btn").click(function () {

        Swal.fire({
        title: "ایجاد سفارش و فاکتور موفق؟",
        text: "با تایید شما، یک سفارش و فاکتور از نوع موفق و پرداخت شده ایجاد و موجودی محصولات نیز بروز خواهند شد",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: "#007bff",
        confirmButtonText: "تایید نهایی",
        cancelButtonText: 'انصراف'
        }).then((result) => {
            if (result.isConfirmed) {

                let final_cart_data     = $("#final_cart_data").val();
                let mos_shipping_method = $("#mos_shipping_method").val();
                let mos_payment_method  = $("#mos_payment_method").val();
                let mos_user_id         = $("#mos_user_id").val();

                $.ajax({
                    type: "POST",
                    dataType: 'text',
                    url: mpPanelBaseUrl + "/physical-order-manual-order-submit",
                    data: {
                        final_cart_data    : final_cart_data,
                        mos_shipping_method: mos_shipping_method,
                        mos_payment_method : mos_payment_method,
                        mos_user_id        : mos_user_id
                    },
                    cache: false,
                    timeout: 30000,
                    success: function (data) { 

                        //empty the curent page
                        $('#final_cart_data').val("[]");
                        renderCartTable();

                        Swal.fire({
                            title: "ثبت سفارش با موفقیت انجام شد",
                            text: "",
                            icon: 'success',
                            showCancelButton: true,
                            confirmButtonColor: "#00a357ff",
                            cancelButtonColor: "#007bff",
                            confirmButtonText: "مشاهده سفارش",
                            cancelButtonText: 'ثبت سفارش جدید'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    window.location.href = mpPanelBaseUrl + "/physical-orders/" + data;
                                }
                            });
            
                    },
                    error: function(e) {
                        notyf.error('Error: ' + e.responseText);
                        gainMOSMainInputFocus();
                    }
            
                });

            }

        });


    });

    
    // setTimeout(function () {
    //     console.log("select mos_user_id");
    //     $('select#mos_user_id').trigger('change').trigger('change.select2');
    // }, 2000);
    

}); //end of jqury doc ready