import {Constants} from './constants';
import {Config} from '../../config';
import {Helpers} from "./helpers";

const moment = require('moment-timezone');
import $ from 'jquery';
import {Components} from "./component";
import EventDetails from '../component/event-details/EventDetails';
import Checkout from '../component/checkout/Checkout';

export class TicketValidation {
    price_calculator_scope = "";

    static inputNumberIncrement(e) {
        TicketValidation.price_calculator_scope = $(e).closest('.price_calculator_scope');
        const $input = $(e).parents('.eb-input-number').find(".ticket_info_quantity");
        const val = parseInt($input.val(), 10);
        $input.val(val + 1);

        TicketValidation.change_ticket_qty($input);
    }

    static inputNumberDecrement(e) {
        TicketValidation.price_calculator_scope = $(e).closest('.price_calculator_scope');
        const $input = $(e).parents('.eb-input-number').find(".ticket_info_quantity");
        const val = parseInt($input.val(), 10);
        if(val > $input.attr('min')){
            $input.val(val - 1);
            TicketValidation.change_ticket_qty($input);
        } else {
            $input.val(0);
            TicketValidation.change_ticket_qty($input);
        }
    }

    static change_ticket_qty($input) {
        const input_class = $($input).attr('data-id');
        let max_input = parseInt($($input).attr('data-max'));
        const data_ticket_type_name = $($input).attr('data-ticket-type');
        const is_item_type_product = $($input).attr('data-is_product');
        const session_id = $($input).attr('data-session_id');
        const occUUID = $($input).attr('data-occ_uuid');
        const isOnlineEvent = $('input[name=is_online_event]').val() === 'true';
        const eventHasSessions = $('input[name=event_has_sessions]').val() === 'true';
        const isOnlineEventTypeEventMeet = $('input[name=is_online_event_type_event_meet]').val() === 'true';

        let isSellTicketByOrg = false;
        let IsAddGuestByOrg = false;

        const total_input = TicketValidation.set_qty(input_class, session_id);

        $(".max-ticket-exceeded-error").remove();

        //start check event order ticket capacity
        const is_enable_event_capacity = $('input[name=is_enable_event_capacity]').val() === 'true';
        const is_enable_session_capacity = $(`input[name=is_enable_session_capacity_${session_id}]`).val() === 'true';

        if ((is_enable_event_capacity && !is_item_type_product) || is_enable_session_capacity) {
            let event_capacity = parseInt($('input[name=event_capacity]').val());
            let event_order_tickets = parseInt($('input[name=event_order_tickets]').val());

            const total_quantity = TicketValidation.getTotalSelectedTicketQty();

            if ((is_enable_event_capacity && !is_item_type_product)) {
                console.log('event_order_tickets', event_order_tickets, 'total_quantity', total_quantity, 'event_capacity', event_capacity, 'input_class', input_class, '$input', $input);
                
                let res = this.eventCapacityErrorResponse(event_order_tickets, total_quantity, event_capacity, $input, input_class);
                if (res === false) {
                    return false;
                }
            }

            // check for session capacity
            if (is_enable_session_capacity) {
                let session_capacity = parseInt($(`input[name=session_capacity_${session_id}]`).val());

                let session_order_tickets = parseInt($(`input[name=session_order_tickets_${session_id}]`).val());
                const session_total_quantity = TicketValidation.getTotalSelectedTicketQty(session_id);

                console.log('session_capacity:', session_capacity, 'session_order_tickets:', session_order_tickets, 'session_total_quantity:', session_total_quantity);
                

                let res = TicketValidation.eventCapacityErrorResponse(session_order_tickets, session_total_quantity, session_capacity, $input, input_class)
                if (res === false) {
                    return false;
                }
            }
        }
        //end check event order ticket capacity

        // start check ticket limit per attendees
        if (!isSellTicketByOrg && !IsAddGuestByOrg) {
            const is_enable_ticket_purchase_limit_per_attendees = $('input[name=is_enable_ticket_purchase_limit_per_attendees]').val() === 'true';
            const is_logged_in = $('input[name=is_logged_in]').val();

            if (is_enable_ticket_purchase_limit_per_attendees) {
                let ticket_limit_per_attendees = parseInt($('input[name=ticket_limit_per_attendees]').val());
                // let user_event_order_tickets = parseInt($('input[name=user_event_order_tickets]').val());
                let user_event_order_tickets = 0;

                let total_quantity = TicketValidation.getTotalSelectedTicketQty();
                if (!is_item_type_product) {
                    let res = TicketValidation.ticketLimitPerAttendeesErrorResponse(user_event_order_tickets, total_quantity, ticket_limit_per_attendees, $input, input_class);

                    if (res === false) {
                        return false;
                    }
                }
            }
            // end check ticket limit per attendees
        }

        //start check ticket order capacity
        //its work for variation tickets
        const is_enable_ticket_capacity = $(`input[name=${input_class}_is_enable_ticket_capacity]`).val() === 'true';        
        if (is_enable_ticket_capacity) {
            let dynamic_session_condition = '';
            if (session_id) {
                dynamic_session_condition = `[data-session_id=${session_id}]`;
            }

            const ticket_capacity = parseInt($(`input[name=${input_class}_ticket_capacity] ${dynamic_session_condition}`).val());
            const total_order_tickets = parseInt($(`input[name=${input_class}_total_order_tickets] ${dynamic_session_condition}`).val());
            console.log('ticket_capacity', ticket_capacity, 'total_order_tickets', total_order_tickets);
            

            let ticket_total_quantity = 0;
            $.each($('.eb_ticket_qty', TicketValidation.price_calculator_scope), function (k, row) {
                const row_session_id = $(row).attr("data-session_id");
                if (session_id && session_id !== row_session_id) {
                    return;
                }

                let quantity = 0;
                if ($(row).val() !== '') {
                    quantity = parseInt($(row).val());
                    // start get totalTicketPerGroup
                    let ticketId = $(row).attr('data-id');
                    if (ticketId != input_class) return;
                    const isGroupVariation = $(row).attr('data-is_group_variation') === 'true';
                    if (isGroupVariation) {
                        ticketId = $(row).attr('data-sub_ticket_id');
                    }
                    const totalTicketPerGroup = $(`.${ticketId}_total_ticket_per_group`).val();
                    if (totalTicketPerGroup > 0) {
                        quantity = quantity * totalTicketPerGroup;
                    }
                    // end get totalTicketPerGroup
                    ticket_total_quantity = ticket_total_quantity + quantity;
                }
            });
            // let total_selected_ticket_count = 0;
            // $.each($('.increment'), function (k, input){
            //     total_selected_ticket_count += parseInt($(input).val());
            // });
            if ((total_order_tickets + parseInt(ticket_total_quantity)) > ticket_capacity) {
                const val = parseInt($input.val(), 10);
                $input.val(val - 1);

                let error_msg = 'You have added all the remaining tickets';

                if ($input.val() === '0') {
                    error_msg = "There are no tickets available to add.";
                }

                const span = $($input).closest('.eb_ticket_main_wrap').find('.insert_error_after');
                $("<div>").addClass("max-ticket-exceeded-error").html(error_msg).insertAfter(span);
                TicketValidation.set_qty(input_class);
                return false;
            }
        }
        //end check event order ticket capacity

        const isGroupVariationTicket = $($input).attr('data-is_group_variation') === 'true';

        if (isGroupVariationTicket) {
            const totalVariationTicket = TicketValidation.getTotalVariationTicketCount(input_class, session_id);

            if (totalVariationTicket > max_input) {
                const variationTicketId = $($input).attr('data-sub_ticket_id');
                const variationTotalTicketPerGroup = $(`.${variationTicketId}_total_ticket_per_group`).val();

                let current_value = parseInt($($input).val()) - ((totalVariationTicket - max_input) / parseInt(variationTotalTicketPerGroup));
                current_value = parseInt(current_value);

                $($input).val(current_value);

                let error_msg = `You can add a maximum of ${current_value} ticket${current_value > 1 ? 's' : ''} from this ${data_ticket_type_name}`;
                let span = $($input).closest('.eb_ticket_main_wrap').find('.insert_error_after')
                $("<div>").addClass("max-ticket-exceeded-error").html(error_msg).insertAfter(span);

                TicketValidation.set_qty(input_class);
            } else {
                TicketValidation.set_qty(input_class);
            }
        } else {
            if (isOnlineEvent && isOnlineEventTypeEventMeet && eventHasSessions) {
                max_input = max_input * TicketValidation.getHowManySessionAssociateWithTheTicket($input);
            }

            if (parseInt(total_input) > parseInt(max_input)) {
                const current_value = parseInt($($input).val()) - (total_input - max_input);
                $($input).val(current_value);
                console.log('Reached max number of input');
                //var error_msg = 'You can select max '+max_input+' '+data_ticket_type_name+' tickets';
                let error_msg = `You can add a maximum of ${current_value} ticket${current_value > 1 ? 's' : ''} from this ${data_ticket_type_name}.`;

                if (is_item_type_product) {
                    error_msg = `You can add a maximum of ${current_value} product${current_value > 1 ? 's' : ''} from this ${data_ticket_type_name}.`;
                }

                const span = $($input).closest('.eb_ticket_main_wrap').find('.insert_error_after');

                const ticket_error = $("<div>").addClass("max-ticket-exceeded-error").html(error_msg).insertAfter(span);

                TicketValidation.set_qty(input_class);
            } else {
                TicketValidation.set_qty(input_class);
            }
        }

        const isMerchandiseProduct = $($input).attr('data-is_merchandise');

        if (!isMerchandiseProduct) {
            TicketValidation.checkOnlineEventMaxOneTicket($input);
        }

        TicketValidation.calculate_total_price(occUUID);
    }

    static getHowManySessionAssociateWithTheTicket($input) {
        const targetInputTicketId = $($input).attr('data-ticket');

        let howManySessionAssociateWithThisTicket = 0;
        $('.ticket_info_quantity').each(function (k, ticketInfoQuantity) {
            if ($(ticketInfoQuantity).attr('data-ticket') == targetInputTicketId) {
                howManySessionAssociateWithThisTicket++
            }
        })

        return howManySessionAssociateWithThisTicket;
    }

    static calculate_total_price(occUUID=null, timeslotUUID=null) {
        let total_quantity = 0;
        let total_product_quantity = 0;
        let total_price = 0;
        let total_fee = 0;
        let sessionIdArr = [];

        $.each($('.eb_ticket_qty', TicketValidation.price_calculator_scope), function (k, row){
            const rowOccUUID = $(row).attr("data-occ_uuid");
            const rowTimeslotUUID= $(row).attr("data-timeslot_uuid");
    
            if ((!Helpers.isEmpty(occUUID) && occUUID !== rowOccUUID) || (!Helpers.isEmpty(timeslotUUID) && timeslotUUID !== rowTimeslotUUID)) {
                return;
            }

            let price = $(this).attr('data-price');
            let quantity = 0;

            const fee_amount = parseFloat($(this).attr('data-fee-amount'));
            price = parseFloat(price) + fee_amount;

            if($(row).val() !== '' && $(row).val() !== '0' && $(row).val() !== 0) {
                quantity = parseInt($(row).val());
                total_price = total_price + (quantity*price);

                // start get totalTicketPerGroup
                let ticketId = $(row).attr('data-id');
                const isGroupVariation = $(row).attr('data-is_group_variation') === 'true';

                if (isGroupVariation) {
                    ticketId = $(row).attr('data-sub_ticket_id');
                }

                const totalTicketPerGroup = $(`.${ticketId}_total_ticket_per_group`).val();

                if (totalTicketPerGroup > 0) {
                    quantity = quantity * totalTicketPerGroup;
                }
                // end get totalTicketPerGroup

                total_quantity = total_quantity + quantity;

                let isProduct = $(this).attr('data-is_product') === 'true';
                if (isProduct) {
                    total_product_quantity = total_product_quantity + quantity;
                }

                if(quantity>0) {
                    total_fee = total_fee + (parseInt($(row).val())*fee_amount);
                }

                if ($(row).attr('data-session_id')) {
                    sessionIdArr.push($(row).attr('data-session_id'));
                }
            }
        });

        if (total_quantity > total_product_quantity) {
            total_quantity = total_quantity - total_product_quantity;
        } else {
            total_quantity = total_product_quantity - total_quantity;
        }

        let price_calculator_scope = TicketValidation.price_calculator_scope;
        let getDisplayPrice = TicketValidation.getDisplayPrice;
        let formatNumberIntoCommaSeparator = TicketValidation.formatNumberIntoCommaSeparator;

        // $('.display_total_quantity', price_calculator_scope).html(total_quantity);
        if(total_price == 0 && 0){
            $('.display_total_price', price_calculator_scope).html(0);
        } else {
            $('.display_total_price', price_calculator_scope).html(getDisplayPrice(total_price));
        }


        if(total_quantity == 0){
            $('.selected-ticket-wrapper', price_calculator_scope).hide().find('span').first().text(formatNumberIntoCommaSeparator(total_quantity));

        } else {
            $('.selected-ticket-wrapper', price_calculator_scope).show().find('span').first().text(formatNumberIntoCommaSeparator(total_quantity));

            if(total_quantity> 1){
                $('.selected-ticket-wrapper', price_calculator_scope).find('span').last().text('s');
            }else{
                $('.selected-ticket-wrapper', price_calculator_scope).find('span').last().text('');
            }
        }

        if(total_product_quantity == 0){
            $('.selected-merchandise-wrapper', price_calculator_scope).hide().find('span').text(total_product_quantity);
        } else {
            $('.selected-merchandise-wrapper', price_calculator_scope).show().find('span').text(total_product_quantity);
            if(total_product_quantity > 1){
                $('.selected-merchandise-wrapper', price_calculator_scope).find('span').last().text('s');
            }else{
                $('.selected-merchandise-wrapper', price_calculator_scope).find('span').last().text('');
            }
        }

        let total_session_quantity_arr = new Set(sessionIdArr);
        let total_session_quantity = total_session_quantity_arr.size;

        if(total_session_quantity == 0){
            $('.selected-session-wrapper', price_calculator_scope).hide().find('span').first().text(total_session_quantity);
        } else {
            $('.selected-session-wrapper', price_calculator_scope).show().find('span').first().text(total_session_quantity);
            if(total_session_quantity > 1){
                $('#session_count').text(`${total_session_quantity} sessions`)
                $('.selected-session-wrapper', price_calculator_scope).find('span').last().text('s');
            }else{
                $('#session_count').text(`${total_session_quantity} session`)
                $('.selected-session-wrapper', price_calculator_scope).find('span').last().text('');
            }
        }
    }

    static checkOnlineEventMaxOneTicket($input) {
        const isOnlineEvent = $('input[name=is_online_event]').val() === 'true';
        const isOnlineEventTypeEventMeet = $('input[name=is_online_event_type_event_meet]').val() === 'true';

        if (isOnlineEvent && isOnlineEventTypeEventMeet) {
            const inputVal = $($input).val();

            if (inputVal >= 1) {
                $($input).val(1);
                $($input).next('.input-number-increment').addClass('eb-disabled-all');
            } else {
                $($input).next('.input-number-increment').removeClass('eb-disabled-all');
            }

            $('.eb_ticket_qty').not($input).each(function (key, element) {
                const isMerchandiseProduct = $(element).attr('data-is_merchandise');

                if (isMerchandiseProduct) {
                    return;
                }

                const targetInputSessionId = $($input).attr('data-session_id');
                if (targetInputSessionId) {
                    const elementSessionId = $(element).attr('data-session_id');

                    if (targetInputSessionId !== elementSessionId) {
                        return;
                    }
                }

                let parentClass = '.eb-input-number';

                // @TODO:
                if ($(element).attr('data-is_donation_ticket')) {
                    parentClass = '.input-group'
                }

                if (inputVal >= 1) {
                    $(element).parents(parentClass).addClass('eb-disabled-all');
                    // if ($(element).attr('data-is_donation_ticket')) {
                    //     $(element).parents(parentClass).parents('.manage-input-number').find('.slider-container').addClass('disabled-all');
                    // }

                } else {
                    $(element).parents(parentClass).removeClass('eb-disabled-all');
                    // if ($(element).attr('data-is_donation_ticket')) {
                    //     $(element).parents(parentClass).parents('.manage-input-number').find('.slider-container').removeClass('disabled-all');
                    // }
                }
            })
        }
    }

    static submitTicketForm(occUUID=null, timeslotUUID=null) {
        let isSellTicketByOrg = false;
        let IsAddGuestByOrg = false;

        TicketValidation.price_calculator_scope = $(".ticketSubmitBtn").closest('.price_calculator_scope');
        let price_calculator_scope = TicketValidation.price_calculator_scope;

        const ticket_info_quantity = $(".ticket_info_quantity", price_calculator_scope);
        if (ticket_info_quantity.length == 0) {
            // customToast('error',no_ticket_found_msg);
            alert("error message");
            return false;
        }

        let invalid = true;
        ticket_info_quantity.each(function () {
            let val = parseInt($(this).val());
            if (isNaN(val) || val < 0) {
                val = 0;
                $(this).val("");
            }

            if (val > 0) {
                invalid = false;
            }
        })

        if (invalid) {
            alert("Please add a ticket");

            // customToast('error','Please add a ticket');
            return false;
        }

        const eventHasProducts = $('input[name=event_has_products]').val() === 'true';

        const eventHasSessions = $('input[name=event_has_sessions]').val() === 'true';
        const eventSessionCount = $('input[name=event_session_count]').val();
        const isEnableTicketMandatory = $('input[name=is_enable_ticket_mandatory]').val() === 'true';
        const atlestOneSessionEnableForSell = eventHasSessions && eventSessionCount > 1;
        // const isEventSellAppointment = $('input[name=is_event_sell_appointment]').val();

        // start validate min ticket qty
        if (!isSellTicketByOrg && !IsAddGuestByOrg && isEnableTicketMandatory) {
            let invalid = false;

            $(".max-ticket-exceeded-error").remove();

            ticket_info_quantity.each(function () {
                const isMerchandise = $(this).attr('data-is_merchandise') === 'true';

                if (!isMerchandise) {
                    const isHidden = $(this).parents(".eb_single_ticket_wrapper").hasClass("eb-d-none");
                    if (isHidden) {
                        return;
                    }

                    let val = parseInt($(this).val());
                    const minPerOrder = $(this).attr('data-min');
                    const ticketId = $(this).attr('data-ticket');
                    const mustBePurchase = $(this).attr('data-mus-be-purchase') === 'true';

                    const totalTicketPerGroup = $(`.${ticketId}_total_ticket_per_group`).val();
                    if (totalTicketPerGroup > 0) {
                        val = val * totalTicketPerGroup;
                    }

                    if ((mustBePurchase && minPerOrder && val < minPerOrder) || (!mustBePurchase && minPerOrder && val > 0 && val < minPerOrder) ) {
                        const $input = this;

                        let mandatory_dynamic_text = mustBePurchase ? "mandatory" : "minimum quantity of";

                        const error_msg = `To attend this event, you must buy the ${mandatory_dynamic_text} ticket${minPerOrder > 1 ? 's' : ''}. Review your selection and try again.`;

                        const span = $($input).closest('.eb_ticket_main_wrap').find('.insert_error_after');
                        $("<div>").addClass("max-ticket-exceeded-error").html(error_msg).insertAfter(span);

                        invalid = true
                    }
                }
            })

            if (invalid) {
                return false;
            }
        }
        // end validate min ticket qty

        // start validate min per order when open merchants products form
        const isOpenProductForm = eventHasProducts && !$('#ebMerchantProductsSection').hasClass('eb-d-none');
        if (!isSellTicketByOrg && !IsAddGuestByOrg && eventHasProducts && isOpenProductForm) {
            let invalid = false;

            $(".max-ticket-exceeded-error").remove();

            ticket_info_quantity.each(function () {
                const isMerchandise = $(this).attr('data-is_merchandise') === 'true';

                if (isMerchandise) {
                    const val = parseInt($(this).val());
                    const minPerOrder = $(this).attr('data-min');

                    if (minPerOrder && val < minPerOrder) {
                        const $input = this;
                        const error_msg = `To attend this event, you must buy the minimum of ${minPerOrder} product${minPerOrder > 1 ? 's' : ''}. Review your selection and try again.`;

                        const span = $($input).closest('.eb_ticket_main_wrap').find('.insert_error_after');
                        $("<div>").addClass("max-ticket-exceeded-error").html(error_msg).insertAfter(span);

                        invalid = true
                    }
                }
            })

            if (invalid) {
                return false;
            }
        }
        // end validate min per order when open merchants products form


        const isOpenedAddMoreSessionModal = !$("#addMoreSessionModal").hasClass("eb-d-none");

        const isSelectedAllSessions = TicketValidation.checkIsSelectedAllSessions()

        if (!isSelectedAllSessions && atlestOneSessionEnableForSell && !isOpenedAddMoreSessionModal && !isOpenProductForm) {
            Helpers.openModal("#addMoreSessionModal");

        } else if (eventHasProducts && !isOpenProductForm) {
            Helpers.closeModal("#addMoreSessionModal");

            TicketValidation.showEventMerchantProducts();

        } else {
            let postData = $('#ticketForm').serializeArray();
            let preparedReqData = this.prepareSubmitedFormData(postData, occUUID);

            let eb_occ_start_on = null;
            if(Helpers.isRecurringEvent(eventDetails)){
                let selectedOccurrence = Helpers.getOccurrenceDetailsByUuid(eventDetails, occUUID);
                if (selectedOccurrence) {
                    eb_occ_start_on = selectedOccurrence?.start_on?.utc;
                }                
            }

            const ticketData = {
                timeslot_uuid: timeslotUUID,
                occurrence_uuid: occUUID,
                event_start_on: eb_occ_start_on,
                line_items: preparedReqData,
            }  
            
            console.log('ticketData');
            console.log(ticketData);
            
            window.bookNowCallback?.(ticketData);
            
            // const checkOutHtml = Checkout({
            //     ticketData: ticketData,
            //     eventDetails: eventDetails,
            //     orderPayloadCallback: (orderPayload)=>{

            //     }
            // });

            // $('.eb-event-details-wrapper').addClass('eb-d-none');
            // $('.eb-event-checkout-wrapper').html(checkOutHtml).removeClass('eb-d-none');
            // $('.eb-event-checkout-wrapper').removeClass('eb-d-none');
            //--------->

            $('body').removeClass('eb-modal-open');
        }
    }

    static parseName(name) {
        // Split the string by '[' and ']' to extract the parts
        const parts = name.split(/[\[\]]/).filter(part => part !== "");
    
        if (parts[0] !== "ticket_info" && parts[0] !== "merchant_product_info") return null;

        let res = {};
        let key = 0;
        for (const ele of parts) {
            if(ele == 'ticket_info'){
                res.ticketId = parts[key+1];
            }else if(ele == 'subtype'){
                res.subtypeId = parts[key+1];
            }else if(ele == 'quantity'){
                res.field = ele;
                res.sessionId = Helpers.isEmpty(parts[key+1])?null:parts[key+1];
                break;
            }else if(ele == 'total_ticket_per_group'){
                res.field = ele;
            }else if(ele == 'merchant_product_info'){
                res.productId = res.ticketId = parts[key+1];
            }else if(ele == 'donation_amount'){
                res.field = ele;
                res.sessionId = Helpers.isEmpty(parts[key+1])?null:parts[key+1];
                break;
            }
            key++;
        }
    
        return res;
    }

    static prepareSubmitedFormData(postData, occUUID=null) {
        const transformedData = {};

        // Step 1: Transform form data into a structured object
        postData.forEach(({ name, value }) => {
            const parsed = this.parseName(name);
            if (!parsed) return;

            const { ticketId, subtypeId, sessionId, productId, field } = parsed;

            if (!transformedData[ticketId]) {
                transformedData[ticketId] = { id: ticketId };
            }

            if (subtypeId) {
                transformedData[ticketId].subtype = transformedData[ticketId].subtype || {};
                transformedData[ticketId].subtype[subtypeId] = transformedData[ticketId].subtype[subtypeId] || { id: subtypeId };
                if(sessionId){
                    transformedData[ticketId].subtype[subtypeId].sessions = transformedData[ticketId].subtype[subtypeId].sessions || {};
                    transformedData[ticketId].subtype[subtypeId].sessions[sessionId] = transformedData[ticketId].subtype[subtypeId].sessions[sessionId] || {};
                    transformedData[ticketId].subtype[subtypeId].sessions[sessionId][field] = value;
                }else{
                    transformedData[ticketId].subtype[subtypeId][field] = value;
                }
            } else {
                if(sessionId){
                    transformedData[ticketId].sessions = transformedData[ticketId].sessions || {};
                    transformedData[ticketId].sessions[sessionId] = transformedData[ticketId].sessions[sessionId] || {};
                    transformedData[ticketId].sessions[sessionId][field] = value;
                }else{
                    transformedData[ticketId][field] = value;
                    transformedData[ticketId].is_merchandise = Helpers.isEmpty(productId)?false:true;
                }
            }
        });

        console.log('transformedData', transformedData, 'postData', postData);

        // Step 2: Flatten the transformed data into the desired format
        let serial = 0;
        const result = Object.entries(transformedData).flatMap(([ticketId, item]) => {
            let { subtype, quantity, sessions, is_merchandise, donation_amount } = item;

            if(!Helpers.isEmpty(donation_amount)){
                let fee = Helpers.feesCalculator(donation_amount, null, null, eventDetails);        
                donation_amount = parseFloat(donation_amount.replace(/,/g, '')) + fee;
            }            

            let ticket = eventDetails?.tickets?.levels.find(ticket=>ticket.uuid==ticketId);

            if (!Helpers.isEmpty(subtype)){            
                let haveSession = Helpers.isEmpty(Object.entries(subtype).pop()[1].sessions)?false:true;
                if(haveSession){
                    return Object.entries(subtype)
                        .flatMap(([subtypeId, subItem]) => {
                            return Object.entries(subItem.sessions) // Iterate over all sessions
                                .filter(([, session]) => Number(session.quantity) > 0) // Only include sessions with quantity > 0
                                .map(([session_uuid, session]) => {
                                    if(!Helpers.isEmpty(occUUID) && occUUID != session_uuid.split("_")[1]) return null;

                                    let subTicket = ticket.pricing_details?.find(sub => sub.uuid === subtypeId);
                                    
                                    return {
                                        serial: ++serial, // Increment serial number
                                        product: subtypeId, // Subtype UUID
                                        session_uuid: session_uuid.split("_")[0], // Session UUID
                                        type: "ticket", // Fixed type
                                        quantity: Number(session.quantity), // Quantity from session
                                        quantity_included: subTicket?.quantity_included || null, // From pricing_details
                                        formeo_ticket_slug: subTicket?.formeo_ticket_slug || null // From pricing_details
                                    };
                                })
                                .filter(Boolean);
                        });

                }else{
                    return Object.entries(subtype)
                        .filter(([, subItem]) => Number(subItem.quantity) > 0)
                        .map(([subtypeId, subItem]) => {
                            let subTicket = ticket.pricing_details?.find(sub=>sub.uuid==subtypeId);
                            return ({
                                serial: ++serial,
                                product: subtypeId,
                                session_uuid: null,
                                type: "ticket",
                                quantity: Number(subItem.quantity),
                                quantity_included: subTicket?.quantity_included || null,
                                formeo_ticket_slug: subTicket?.formeo_ticket_slug || null
                            });
                        });
                }

            }else if(!Helpers.isEmpty(sessions)){
                return Object.entries(sessions)
                    .filter(([, sesItem]) => Number(sesItem.quantity) > 0)
                    .map(([session_uuid, sesItem]) => {
                        if(!Helpers.isEmpty(occUUID) && occUUID != session_uuid.split("_")[1]) return null;
                        return ({
                            serial: ++serial,
                            product: ticketId,
                            session_uuid: session_uuid.split("_")[0],
                            type: "ticket",
                            quantity: Number(sesItem.quantity),
                            quantity_included: ticket?.pricing_details[0].quantity_included || null,
                            formeo_ticket_slug: ticket?.formeo_ticket_slug || null,
                            price: donation_amount || null
                        });
                    })
                    .filter(Boolean);

            }else if (Number(quantity) > 0) {
                return {
                    serial: ++serial,
                    product: ticketId,
                    session_uuid: null,
                    type: is_merchandise?"merchandise":"ticket",
                    quantity: Number(quantity),
                    quantity_included: ticket?.pricing_details[0].quantity_included || null,
                    formeo_ticket_slug: ticket?.formeo_ticket_slug || null,
                    price: donation_amount || null
                };
            }

            return [];
        });    

        return result;
    }

    static checkIsSelectedAllSessions() {
        let sessionSelectedCount = 0;
        let totalSessionCount = 0;

        $('.eb_single_session_card').each(function (k, session_card) {
            const sessionId = $(session_card).attr("data-session_id");

            let isSessionSelected = false;
            $(`.eb_ticket_session_id_${sessionId}`).find('.eb_ticket_qty').each(function (key, ticket_qty) {
                const isSelected = parseInt($(ticket_qty).val()) > 0;

                if (isSelected) {
                    isSessionSelected = true;
                }
            });

            if (isSessionSelected) {
                sessionSelectedCount++;
            }

            const isSessionNotEnded = $(session_card).find('.eb_session_ended').hasClass('eb-d-none');
            const isSessionNotSoldOut = $(session_card).attr('data-is_sold_out') !== 'true';

            if (isSessionNotEnded && isSessionNotSoldOut) {
                totalSessionCount++;
            }
        })

        return totalSessionCount === sessionSelectedCount;
    }


    static getDisplayPrice(price) {
        return price.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2})
    }

    static formatNumberIntoCommaSeparator(value){
        value = value.toString().replace(/,/g, "");

        if(isNaN(Number(value))){
            return 0
        }

        let formatter = new Intl.NumberFormat('en-US', {
            minimumFractionDigits: 0
        });
        let formattedNumber = formatter.format(value);

        return formattedNumber;
    }

    static onupdateTicketQty(e) {
        const $input = $(e).parents('.eb-input-number').find(".ticket_info_quantity");
        TicketValidation.change_ticket_qty($input);
    }

    static getTotalSelectedTicketQty(session_id) {
        let total_quantity = 0;

        $.each($('.eb_ticket_qty', TicketValidation.price_calculator_scope), function (k, row) {
            const row_session_id = $(row).attr("data-session_id");

            if (session_id && session_id !== row_session_id) {
                return;
            }

            let quantity = 0;

            if ($(row).val() !== '') {
                quantity = parseInt($(row).val());

                // start get totalTicketPerGroup
                let ticketId = $(row).attr('data-id');
                const isGroupVariation = $(row).attr('data-is_group_variation') === 'true';

                if (isGroupVariation) {
                    ticketId = $(row).attr('data-sub_ticket_id');
                }

                const totalTicketPerGroup = $(`.${ticketId}_total_ticket_per_group`).val();

                if (totalTicketPerGroup > 0) {
                    quantity = quantity * totalTicketPerGroup;
                }
                // end get totalTicketPerGroup

                total_quantity = total_quantity + quantity;

            }
        });

        return total_quantity;
    }

    static set_qty(input_class, session_id = "") {

        let total_input = 0;
        $.each($('.' + input_class, TicketValidation.price_calculator_scope), function (k, row) {
            const row_session_id = $(row).attr("data-session_id");

            if (session_id && session_id !== row_session_id) {
                return;
            }

            if ($(row).val() !== '') {
                total_input = total_input + parseInt($(row).val());
            }
        });
        $('.' + input_class + '-qty', TicketValidation.price_calculator_scope).val(total_input);

        return total_input;
    }

    static eventCapacityErrorResponse(event_order_tickets, total_quantity, event_capacity, $input, input_class) {
        if ((event_order_tickets + parseInt(total_quantity)) > event_capacity) {
            const val = parseInt($input.val(), 10);
            $input.val(val - 1);

            let error_msg = 'You have added all the remaining tickets.';

            if (val === 0) {
                error_msg = "There are no tickets available to add.";
            }

            const span = $($input).closest('.eb_ticket_main_wrap').find('.insert_error_after');
            $("<div>").addClass("max-ticket-exceeded-error").html(error_msg).insertAfter(span);

            TicketValidation.set_qty(input_class);

            return false;
        }
    }

    static ticketLimitPerAttendeesErrorResponse(user_event_order_tickets, total_quantity, ticket_limit_per_attendees, $input, input_class) {
        let is_occurrence_event = !!$('input[name=event_occurrence_uuid]').val();

        if ((user_event_order_tickets + parseInt(total_quantity)) > ticket_limit_per_attendees) {
            const val = parseInt($input.val(), 10);
            $input.val(val - 1);

            let event_text = is_occurrence_event ? 'occurrence' : 'event';

            let error_msg = `Each attendee is allowed to purchase up to ${ticket_limit_per_attendees} ticket${ticket_limit_per_attendees > 1 ? 's' : ''} for this ${event_text}.`;

            if (user_event_order_tickets >= ticket_limit_per_attendees) {
                error_msg = `You have already purchased the maximum number of tickets allowed for this ${event_text}.`
            }

            const span = $($input).closest('.eb_ticket_main_wrap').find('.insert_error_after');
            $("<div>").addClass("max-ticket-exceeded-error").html(error_msg).insertAfter(span);

            TicketValidation.set_qty(input_class);

            return false;
        }
    }

    static getTotalVariationTicketCount(input_class, session_id = "") {
        let totalVariationTicket = 0;

        $.each($('.'+input_class, TicketValidation.price_calculator_scope), function (k, row){
            const row_session_id = $(row).attr("data-session_id");
            if (session_id && session_id !== row_session_id) {
                return;
            }

            if($(row).val() !== '') {
                let inputQty = parseInt($(row).val());

                const isGroupVariationTicket = $(row).attr('data-is_group_variation') === 'true';
                if (isGroupVariationTicket) {
                    const groupVariationTicketId = $(row).attr('data-sub_ticket_id');
                    const groupVariationTicketTotalTicketPerGroup = $(`.${groupVariationTicketId}_total_ticket_per_group`).val();

                    inputQty = inputQty*groupVariationTicketTotalTicketPerGroup;

                    totalVariationTicket = totalVariationTicket + inputQty;
                }
            }
        });

        return totalVariationTicket;
    }

    static showEventMerchantProducts() {
        $('#ebMerchantProductsSection').removeClass('eb-d-none');
        $('#ebTicketSection, .ticket_element, .eb-ticket-modal-add-btn-wrap ').addClass('eb-d-none');
        // $('.check-student').text('Checkout')
    }

    static showEventTickets() {
        $('#ebMerchantProductsSection').addClass('eb-d-none');
        $('#ebTicketSection, .ticket_element, .ticket_and_merchandise_element, .eb-ticket-modal-add-btn-wrap ').removeClass('eb-d-none');

        const isEventSellAppointment = $('input[name=is_event_sell_appointment]').val() === 'true';

        if (isEventSellAppointment) {
            $('.ticketSubmitBtn').html($('.timeslot_book_now').text());
        } else {
            $('.ticketSubmitBtn').text('Continue');
        }
    }

    static loadSessionTickets(sessionId, _this) {
        const sessionDateTime = $(_this).attr("data-session_date");
        let sessionTime = sessionDateTime.replace(/\([^)]*\)/, "").trim();
        const sessionDuration = $(_this).attr("data-session_duration").trim();

        $('.eb_active_session_string').text(`${sessionTime} (${sessionDuration})`)

        $('#eventSessionSection, .eb_single_ticket_wrapper').addClass('eb-d-none');
        $(`.eb_ticket_session_id_${sessionId}, .eb_ticket_element`).removeClass('eb-d-none');

        $(".eb_ticket_and_merchandise_element").removeClass("eb-d-none");

        TicketValidation.checkEmptyStateWithTickets(sessionId);
    }

    static checkEmptyStateWithTickets(sessionId) {
        $(".eb_ticket_form_empty_state").addClass("eb-d-none");

        let showEmptyState = true;
        $(`.eb_ticket_session_id_${sessionId}`).each(function (index, element) {
            if (!$(element).hasClass("eb-d-none")) {
                showEmptyState = false;
            }
        })

        if (showEmptyState) {
            $(".eb_ticket_form_empty_state").removeClass("eb-d-none");
        }
    }

    static viewTicketsForSellSession(_this, sessionUUID='', occurrenceUUID='') {
        // let allTickets = eventDetails?.tickets?.levels;
        // let tickets = null;

        // if (!Helpers.isEmpty(sessionUUID)) {
            // let sessions = eventDetails?.sessions?.session_lists;
            // let session = sessions.find(item => item.uuid == sessionUUID);

            // let ticketsData = session?.tickets?.map(item => {
            //     let orgTicket = allTickets.find(ele => ele.uuid == item.uuid);
            //     orgTicket.quantity_sold = item.quantity_sold;
            //     orgTicket.total_purchased_by_user = item.total_purchased_by_user;

            //     let updatedPriceDetails = orgTicket?.pricing_details.map(priceDetails => {
            //         let itemPriceDetails = item?.pricing_details.find(pdItem => pdItem.uuid == priceDetails.uuid);

            //         return {
            //             ...priceDetails,
            //             quantity_sold: itemPriceDetails.quantity_sold
            //         };
            //     });
            //     orgTicket.pricing_details = updatedPriceDetails;

            //     return orgTicket;
            // });
            
            // tickets = {
            //     levels: ticketsData
            // };

        // }

        if(!Helpers.isEmpty(occurrenceUUID)){
            let occurrence = eventDetails.event_occurrence.find(occ => occ.uuid == occurrenceUUID);
            let timezone = Helpers.getTimezoneToConvertDatetime(eventDetails);
            let occStartDate = Helpers.convertTimezone(occurrence.start_on.utc, 'UTC', timezone, 'YYYY-MM-DD HH:mm', 'dddd, MMM D');
            $('.eventHeaderDateTime').text(occStartDate);


            let eventSessions = eventDetails?.sessions?.session_lists;
            let totalActiveSession = occurrence.sessions.reduce((acc, cur) => {
                let session = eventSessions.find(item => item.uuid == cur.uuid);
                return acc += (session.status == Constants.SESSION_ACTIVE ? 1 : 0);                
            }, 0);    
            $("input[name=event_session_count]").val(totalActiveSession);

            $('.occSubBtn').attr('onclick', `TicketValidation.submitTicketForm("${occurrenceUUID}")`);

            $(".eb_ticket_qty").each(function () {
                if ($(this).attr("data-occ_uuid") !== occurrenceUUID) {
                    $(this).val(0);
                }
            });
            this.calculate_total_price(occurrenceUUID);
        }

        $('.backToSessionListFromTicketList').attr('onclick', `TicketValidation.showEventSessionList("${occurrenceUUID}")`);
        $('.addAnotherSession').attr('onclick', `TicketValidation.showEventSessionList("${occurrenceUUID}")`);

        $("#ebTicketSection, .eb_ticket_and_merchandise_element").removeClass("eb-d-none");
        $("#ebMerchantProductsSection").addClass("eb-d-none");
        
        $('.select_session_btn_' + sessionUUID  + (Helpers.isEmpty(occurrenceUUID)?'':'_') + occurrenceUUID).trigger("click");
        Components.openEventTicketPopup(eventDetails);
        return;
        
    }


    static showEventSessionList(occurrenceUUID='') {
        $('#ticketSection, .eb_ticket_element, .eb_single_ticket_wrapper').addClass('eb-d-none');
        $('#eventSessionSection').removeClass('eb-d-none');
        $('.eb_single_session_card').addClass('eb-d-none');
        $('.popupSessionList_'+occurrenceUUID).removeClass('eb-d-none');
        
        $('.eb_ticket_and_merchandise_element').addClass('eb-d-none');

        if(!Helpers.isEmpty(occurrenceUUID)){
            let occurrence = eventDetails.event_occurrence.find(occ => occ.uuid == occurrenceUUID);
            const isMultipleSession = occurrence.sessions.length > 1 ? true:false;
            $('.eb_active_session_string').text(`${isMultipleSession ? 'Multiple Sessions' : 'Session'}`);
        }

        Helpers.closeModal("#addMoreSessionModal");
    }

    static showEventAppointmentCalendar(_this) {
        $(".eb_ticket_element, .eb_ticket_and_merchandise_element").addClass("eb-d-none");
        $(".eb-sell-appointment-main-wrap, .eb_sell_appointment_element").removeClass("eb-d-none");
    }

    static sellAppointmentBookNow(_this) {
        let selectedTimeslotUUID = $(".eb_time_slots.active").attr("data-appointment_uuid");
        let selectedOccurrenceUUID = $(".show_event.active").attr("data-occurrence_uuid");

        let timeSlotTickets = Helpers.getTicketsBySTimeslotUuid(eventDetails, selectedOccurrenceUUID, selectedTimeslotUUID);
        let timeSlotTicketsHtml = Components.getTicketFormHtml(timeSlotTickets, eventDetails, selectedOccurrenceUUID, widgetConfig)

        $("#ticketModalBody").html(timeSlotTicketsHtml);

        $(".eb_ticket_element, .eb_ticket_and_merchandise_element").removeClass("eb-d-none");
        $(".eb-sell-appointment-main-wrap, .eb_sell_appointment_element").addClass("eb-d-none");
        
        let selectedOccurrence = eventDetails.event_occurrence.find(occurrence => occurrence.uuid === selectedOccurrenceUUID);
        let eventOrderTickets = Helpers.getTotalOccurrenceSoldTicket(eventDetails, selectedOccurrence);
        $("input[name=event_order_tickets]").val(eventOrderTickets);

        $('.occSubBtn').attr('onclick', `TicketValidation.submitTicketForm("${selectedOccurrenceUUID}", "${selectedTimeslotUUID}")`);

        TicketValidation.calculate_total_price(selectedOccurrenceUUID, selectedTimeslotUUID);
    }
}

window.TicketValidation = TicketValidation;
