HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/alq-cali.bikenow.co/public/js/web_ticketing.js
selectedTickets = [];
user = null;
activeMatchEvent = null;
tribunes = [];
zones = [];
activeTribune = null;
subTotal = 0;
serviceTotal = 0;
globalTotal = 0;
const userTribuneStatus = {
    userId: null,
    UserDocument: null,
    available_tickets: {}
};
eventData = null;
functionName = null;
const FREE_SALE = 1;
const SUBSCRIBER = 2;
const COMPLIMENTARY = 3;
const CREDIT = 4;

$(document).on('ready', function (e) {
    setCurrencyFormat();

    $('#user_form input[name=email]').on('change input oninvalid focus blur', function () {
        this.setCustomValidity('');
        field = document.getElementById("email");
        if (!field.checkValidity()) {
            field.setCustomValidity('Debes ingresar un formato válido de correo electrónico, por ejemplo: pepitoperez@gmail.com');
        } else if ($('#user_form input[name=confirm_email]').val() && this.value != $('#user_form input[name=confirm_email]').val()) {
            document.getElementById("confirm_email").setCustomValidity('Los correos no coinciden');
        }
    });

    $('#user_form input[name=confirm_email]').on('change input oninvalid focus blur', function () {
        this.setCustomValidity('');
        field = document.getElementById("confirm_email");
        if (!field.checkValidity()) {
            field.setCustomValidity('Debes ingresar un formato válido de correo electrónico, por ejemplo: pepitoperez@gmail.com');
        } else if ($('#user_form input[name=email]').val() && this.value != $('#user_form input[name=email]').val()) {
            field.setCustomValidity('Los correos no coinciden');
        }
    });

    $('#user_form input[name=confirm_email]').on('input', function (event) {
        if (this.value && event.detail == undefined) {
            this.value = '';
        }
    });

    $('#user_form input[name=first_name]').on('change input onkeyup oninvalid focus', function () {
        this.setCustomValidity('');
        if (!this.checkValidity()) {
            this.setCustomValidity('Debes ingresar los nombres del usuario, por ejemplo: Pepito');
        }
    });
    $('#user_form input[name=last_name]').on('change input onkeyup oninvalid focus', function () {
        this.setCustomValidity('');
        if (!this.checkValidity()) {
            this.setCustomValidity('Debes ingresar los apellidos del usuario, por ejemplo: Perez');
        }
    });
    $('#user_form input[name=phone]').on('change input onkeyup oninvalid focus', function (event) {
        this.setCustomValidity('');
        if (!this.checkValidity()) {
            this.setCustomValidity('Debes ingresar un telefono válido, por ejemplo: 3000000001');
        } else if (this.value && this.value.length > 10) {
            this.value = this.value.slice(0, 10);
            event.preventDefault();
            return false;
        }
    });
    $("#modal_sell_seat").on("hidden.bs.modal", function (e) {
        var seat = JSON.parse(localStorage.getItem("current_seat"));
        var is_add_seat = ticketsToBuy.find((item) => item.seat.id == seat.id);
        if (!is_add_seat) {
            $(current_e).removeClass("bg-seat-selected");
        }
    });
})

var me = this;
$(document).on('scroll click', function (e) {
    me.resizePage();
});

function onchangeSelect(sel, event, color) {
    var existIndex = selectedTickets.findIndex(item => item.zone_id === event.zone_id);
    var couponValue = $('#additional-input').val();
    if (existIndex != -1) {
        selectedTickets.splice(existIndex, 1);
    }

    if (sel.value > 0) {
        event['quantity'] = sel.value;
        selectedTickets.push(event);
    }

    html = `
        <div class="row" id="checkout-title" style="color: ` + color + ` ;">
            <div class="col-md-4 col-4">
                <h5>Tribuna</h5>
            </div>
            <div class="col-md-3 col-3 text-center">
                <h5>Precio boleta</h5>
            </div>
            <div class="col-md-2 col-2 text-center">
                <h5>Boletas</h5>
            </div>
            <div class="col-md-3 col-3 text-end">
                <h5>Valor compra</h5>
            </div>
        </div>
    `;

    subTotal = 0;
    serviceTotal = 0;
    globalTotal = 0;
    selectedTickets.forEach(function (element) {
        let oldPrice = element.price
        if (element.apply_coupon_type == 'special_price' && element.coupon == couponValue) {
            element.price = element.special_price
        }
        total = element.quantity * element.price;
        subTotal += total;
        serviceCharge = 0;
        if (element.service_charge) {
            serviceCharge = typeof element.service_charge === 'string' && element.service_charge.includes('%') ? (parseFloat(element.service_charge) / 100) * element.price : element.service_charge;
        }
        serviceTotal += element.quantity * serviceCharge;
        globalTotal = subTotal + serviceTotal;
        html += `
            <hr class="rounded">
            <div class="row">
                <div class="col-md-4 col-4">
                    <h5>` + element.zone + `</h5>
                </div>
                <div class="col-md-3 col-3 text-center">
                    <h5 class="currency">` + element.price + `</h5>
                </div>
                <div class="col-md-2 col-2 text-center">
                    <h5>` + element.quantity + `</h5>
                </div>
                <div class="col-md-3 col-3 text-end">
                    <h5 class="currency">` + total + `</h5>
                </div>
            </div>
        `;
        if (element.apply_coupon_type == 'special_price') {
            element.price = oldPrice
        }
    });

    $("#checkout-body").html(html);
    $("#subtotal").html(subTotal);
    $("#service-total").html(serviceTotal);
    $("#total").html(globalTotal);

    if (selectedTickets.length > 0) {
        $('#buy-btn').show();
    } else {
        $('#buy-btn').hide();
    }
    setCurrencyFormat();
}

function resetSelectedTickets() {
    $("#checkout-body").html('');
    $("#subtotal").html('$0');
    $("#service-total").html('$0');
    $("#total").html('$0');
    selectedTickets = [];
    ticketsToBuy = [];
    $('#buy-btn').hide();
    $('.ticket-select').val(0);
    $("#tribunes-container-coupon").html('');
    $("#additional-input").val('');
    $("#additional-input").prop("disabled", false);
    $("#aplicar-cupon-btn").prop("disabled", false);
}


function getUserByDocument() {
    user = null;
    onChangeId();
    $("#search_button").prop('disabled', true);
    $("#validate_button").prop('disabled', false);

    let documentNumber = $("#document").val();
    $.ajax({
        url: "/user/getByDocument",
        type: "POST",
        data: JSON.stringify({ document: documentNumber }),
        contentType: "application/json",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            "Content-Type": "application/json",
        },
        success: function (r) {
            if (r.length) {
                $('#email-select').empty();

                $('#email-select').append($('<option>', {
                    value: 0,
                    text: 'Seleccione'
                }));

                r.forEach(function (user) {
                    emailSplit = user.email.split('@');
                    $('#email-select').append($('<option>', {
                        value: JSON.stringify(user),
                        text: emailSplit[0]?.replace(/.(?=.{5})/g, '*') + '@' + emailSplit[1]
                    }));
                });

                $('#email-select').append($('<option>', {
                    value: -1,
                    text: 'Otro'
                }));

                $('#email-select').show();
            } else {
                $("#email").prop('disabled', false);
                $("#confirm_email").prop('disabled', false);
                $("#first_name").prop('disabled', false);
                $("#last_name").prop('disabled', false);
                $("#phone").prop('disabled', false);

                $("#confirm_email").prop('required', true);
                $("#first_name").prop('required', true);
                $("#last_name").prop('required', true);
                $("#email").prop('required', true);
                $("#phone").prop('required', true);

                $('#email').show();
                $('#user-info-container').show();
                $('#user-info-footer').show();
            }

            $('#email-container').show();
        }
    });
}

function onSelectedEmail(selection) {
    user = null;
    selected = JSON.parse(selection.value);

    $("#confirm_email").prop('required', true);
    $("#first_name").prop('required', true);
    $("#last_name").prop('required', true);
    $("#phone").prop('required', true);

    if (selected == -1) {
        $('#email').show();

        $("#document").prop("type", "number");
        $("#phone").prop("type", "number");
        $('#email').val('');
        $('#confirm_email').val('');
        $('#first_name').val('');
        $('#last_name').val('');
        $('#phone').val('');

        $("#email").prop('disabled', false);
        $("#confirm_email").prop('disabled', false);
        $("#first_name").prop('disabled', false);
        $("#last_name").prop('disabled', false);
        $("#phone").prop('disabled', false);
    } else {
        $('#email').hide();
        user = selected.id;

        $("#phone").prop("type", "text");
        $('#first_name').val(selected.first_name?.replace(/.(?=.{4})/g, '*'));
        $('#last_name').val(selected.last_name?.replace(/.(?=.{4})/g, '*'));
        $('#phone').val(selected.phone?.replace(/.(?=.{4})/g, '*'));
        $('#email').val(selected.email);
        emailSplit = selected.email.split('@');
        $('#confirm_email').val(emailSplit[0]?.replace(/.(?=.{5})/g, '*') + '@' + emailSplit[1]);

        $("#confirm_email").prop('disabled', true);
        $("#first_name").prop('disabled', true);
        $("#last_name").prop('disabled', true);
        $("#phone").prop('disabled', true);
    }

    $('#user-info-container').show();
    $('#user-info-footer').show();
    $('#tribunes').hide();
    resetSelectedTickets();
    $("#validate_button").prop('disabled', false);
}

function getAvailableTickets(event, skipEmailValidation = false) {
    if (!$("#email").val()) {
        return;
    }
    if (!user && !skipEmailValidation) {
        eventData = event;
        functionName = 'getAvailableTickets';
        sendCodeEmailValidation();
        return;
    }

    resetSelectedTickets();
    $("#email").prop('disabled', true);
    $("#confirm_email").prop('disabled', true);
    $("#first_name").prop('disabled', true);
    $("#last_name").prop('disabled', true);
    $("#phone").prop('disabled', true);
    $("#validate_button").prop('disabled', true);
    if (user) {
        $.ajax({
            url: "/ticket/getAvailableTickets/" + event.match_event_id + "/" + user,
            type: "GET",
            contentType: "application/json",
            async: false,
            headers: {
                "Content-Type": "application/json",
            },
            success: function (r) {
                if (r.length) {
                    userTribuneStatus.available_tickets = {};
                    r.forEach(function (element) {
                        if (element.available_tickets < 1) {
                            $('#amount-' + element.id).hide();
                        } else {
                            html = '';
                            for (i = 0; i <= element.available_tickets; i++) {
                                html += '<option value=' + i + '>' + i + '</option>';
                            }
                            $('#select-' + element.id).html(html);
                            $('#select-' + element.id).val(0);
                        }
                        userTribuneStatus.available_tickets[element.id] = element.available_tickets;
                    });
                    userTribuneStatus.userId = user;
                    userTribuneStatus.UserDocument = $('#document').val();
                }
            }
        });
    }
    $('#tribunes').show();
}

function sendCodeEmailValidation() {
    $.ajax({
        url: "/api/email-validation/send-code",
        type: "POST",
        contentType: "application/json",
        async: false,
        headers: {
            "Content-Type": "application/json",
        },
        data: JSON.stringify({ email: $("#email").val() }),
        success: function (r) {
            showEmailValidationModal();
            if (r.data && r.data.message) {
                showSwal('success', r.data.message);
            }
        }
    });
}

function verifyCode() {
    $("#email-validation-error").hide();
    $.ajax({
        url: "/api/email-validation/verify-code",
        type: "POST",
        contentType: "application/json",
        async: false,
        headers: {
            "Content-Type": "application/json",
        },
        data: JSON.stringify({ email: $("#email").val(), code: $("#code").val() }),
        success: function (r) {
            if (r.status && r.status == 'fail') {
                $("#email-validation-error").show();
                if (r.data && r.data.message) {
                    showSwal('error', r.data.message);
                }
            } else {
                if (r.data && r.data.message) {
                    showSwal('success', r.data.message);
                }
                hideEmailValidationModal();
                continueBuy();
            }
        }
    });
}

function resendCode() {
    $.ajax({
        url: "/api/email-validation/send-code",
        type: "POST",
        contentType: "application/json",
        async: false,
        headers: {
            "Content-Type": "application/json",
        },
        data: JSON.stringify({ email: $("#email").val() }),
        success: function (r) {
            if (r.data && r.data.message) {
                showSwal('success', r.data.message);
            }
        }
    });
}

function continueBuy() {
    switch (functionName) {
        case 'getAvailableTickets':
            getAvailableTickets(eventData, skipEmailValidation = true);
            break;

        case 'loadStadiumZones':
            loadStadiumZones(eventData, skipEmailValidation = true);
            break;
    }
}

function createClient() {
    activateLoadingButton($("#buy_button"), $("#loading_button"));
    if (!user) {
        $("#email").prop('disabled', false);
        $("#confirm_email").prop('disabled', false);
        $("#first_name").prop('disabled', false);
        $("#last_name").prop('disabled', false);
        $("#phone").prop('disabled', false);
        data = buildInfoForApi('#user_form');
        $.ajax({
            url: '/clients/create/true/false',
            type: "POST",
            contentType: "application/json",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                "Content-Type": "application/json"
            },
            data: JSON.stringify(data),
            success: function (r) {
                $("#email").prop('disabled', true);
                $("#confirm_email").prop('disabled', true);
                $("#first_name").prop('disabled', true);
                $("#last_name").prop('disabled', true);
                $("#phone").prop('disabled', true);

                user = r.d;
                if (r.r) {
                    if (ticketsToBuy.length)
                        createBlocks();
                    else
                        validateSeatsAvailableByCapacity();
                } else {
                    Swal.fire("Error", r.m, "error");
                    activateLoadingButton($("#buy_button"), $("#loading_button"), false);
                }
            },
            error: function (e) {
                $("#email").prop('disabled', true);
                $("#confirm_email").prop('disabled', true);
                $("#first_name").prop('disabled', true);
                $("#last_name").prop('disabled', true);
                $("#phone").prop('disabled', true);

                Swal.fire("Error", "¡Hubo un error al crear el usuario!", "error");
                activateLoadingButton($("#buy_button"), $("#loading_button"), false);
            },
        });
    } else {
        if (typeof user == 'number')
            user = { id: user };
        validateSeatsAvailableByCapacity();
    }
}

function validateSeatsAvailableByCapacity() {
    let data = selectedTickets;
    $.ajax({
        url: '/api/flash_tickets/validateSeatsAvailableByCapacity',
        type: "POST",
        contentType: "application/json",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            "Content-Type": "application/json"
        },
        data: JSON.stringify(data),
        success: function (r) {
            if (r) {
                createBlocks(r);
            } else {
                Swal.fire("Error", r.m, "error");
                activateLoadingButton($("#buy_button"), $("#loading_button"), false);
            }
        },
        error: function (e) {
            Swal.fire("Error", "¡Hubo un error No hay sillas disponibles para la tribuna!", "error");
            activateLoadingButton($("#buy_button"), $("#loading_button"), false);
        },
    });
}

function createBlocks(tribunes = []) {
    var tickets = [];
    if (ticketsToBuy.length) {
        tickets = ticketsToBuy;
    } else {
        var couponValue = $('#additional-input').val();
        for (i = 0; i < tribunes.length; i++) {
            element = tribunes[i];
            seats = element.seats;
            let oldPrice = element.price
            if (element.apply_coupon_type == 'special_price' && element.coupon == couponValue) {
                element.price = element.special_price
            }
            if (Array.isArray(seats)) {
                seats.forEach(function (seat) {
                    tickets.push({
                        'seat': {
                            'id': seat.id,
                            'zone_id': seat.zone_id
                        },
                        'match_event_id': element.match_event_id,
                        'ticket_type_id': 1,
                        'price': element.price
                    });
                });
            } else {
                Swal.fire("Advertencia", "No hay sillas disponibles para la tribuna: " + element.zone, "warning");
                activateLoadingButton($("#buy_button"), $("#loading_button"), false);
                return;
            }
            if (element.apply_coupon_type == 'special_price') {
                element.price = oldPrice
            }
        }
    }

    let data = {
        tickets: tickets,
        type_process: "block",
        subtotal: subTotal,
        serviceCharge: serviceTotal,
        amount: globalTotal,
        ticket_type_id: 1,
        season_id: tribunes.length ? tribunes[0].season_id : null
    };


    $.ajax({
        url: '/api/tickets/createBlocks/' + user.id + '/web',
        type: "POST",
        contentType: "application/json",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            "Content-Type": "application/json"
        },
        data: JSON.stringify(data),
        success: function (r) {
            if (r.r) {
                activateLoadingButton($("#buy_button"), $("#loading_button"), false);
                window.open("../../payment_gateway/selection/ticket/" + r.data, "_self")
            } else {
                Swal.fire("Advertencia", r.m, "warning");
                activateLoadingButton($("#buy_button"), $("#loading_button"), false);
            }
        },
        error: function (e) {
            Swal.fire("Error", "¡Hubo un error al comprar boletas!", "error");
            activateLoadingButton($("#buy_button"), $("#loading_button"), false);
        },
    });
}

function setCurrencyFormat() {
    $(".currency").each(function () {
        let originalValue = $(this).html() || 0;
        if (!isNaN(originalValue)) {
            $(this).html(currencyMask(originalValue));
        }
    });
}

function currencyMask(data) {
    const formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 0,
        maximumFractionDigits: 2,
    });
    return formatter.format(data);
}

function showEmailValidationModal() {
    $('#email-validation').modal({
        backdrop: 'static',
        keyboard: false
    });
}

function hideEmailValidationModal() {
    $('#email-validation').modal('hide');
}

function showSwal(icon, title) {
    Swal.fire({
        position: 'top-end',
        icon: icon,
        title: title,
        showConfirmButton: false,
        timer: 3000
    });
}

function onChangeId() {
    if (!$('#document').val().length) {
        $("#search_button").prop('disabled', true);
    } else {
        $("#search_button").prop('disabled', false);
    }

    $('#email').val('');
    $('#confirm_email').val('');
    $('#first_name').val('');
    $('#last_name').val('');
    $('#phone').val('');

    $("#confirm_email").prop('required', false);
    $("#first_name").prop('required', false);
    $("#last_name").prop('required', false);
    $("#phone").prop('required', false);

    $('#email').hide();
    $('#email-select').hide();
    $('#email-container').hide();
    $('#user-info-container').hide();
    $('#user-info-footer').hide();
    $('#tribunes').hide();

    resetSelectedTickets();
    $("#tribunes-container").find('[id^="amount-"]').each(function (element, val) {
        $(val).show();
    });
}

function activateLoadingButton(actionButton, loadingButton, activated = true, time = 3000) {
    if (activated) {
        actionButton.addClass("hide");
        loadingButton.removeClass("hide");
    } else {
        setTimeout(function () {
            actionButton.removeClass("hide");
            loadingButton.addClass("hide");
        }, time);
    }
}

function showStadiumZones(event = null) {
    if (ticketsToBuy.length)
        Swal.fire('Estás seguro de cambiar de sector, ya que esta acción eliminara las sillas seleccionadas?', {
            closeOnClickOutside: false,
            icon: "warning",
            buttons: {
                cancel: {
                    text: "No",
                    value: false,
                    visible: true,
                    className: "",
                    closeModal: true,
                },
                confirm: {
                    text: "Si, estoy seguro",
                    value: true,
                    visible: true,
                    className: "",
                    closeModal: true
                }
            },
        }).then((confirm) => {
            if (confirm) {
                ticketsToBuy = [];
                validateCheckout();
                loadStadiumZones(event);
            }
        });
    else
        loadStadiumZones(event);
}

function loadStadiumZones(event = null, skipEmailValidation = false) {
    if (!user && !skipEmailValidation) {
        eventData = event;
        functionName = 'loadStadiumZones';
        sendCodeEmailValidation();
        return;
    }

    resetSelectedTickets();
    hideContainers();
    if (event) {
        if (!event.id) {
            event.id = event.event_id;
        }
        activeMatchEvent = event;
    }
    $("#email").prop('disabled', true);
    $("#confirm_email").prop('disabled', true);
    $("#first_name").prop('disabled', true);
    $("#last_name").prop('disabled', true);
    $("#phone").prop('disabled', true);
    $("#validate_button").prop('disabled', true);
    var me = this;
    $.ajax({
        url: `/tickets/loadStadiumZones`,
        type: "GET",
        contentType: "application/json",
        async: false,
        headers: {
            "Content-Type": "application/json",
        },
        data: {
            matchEventId: activeMatchEvent.event_id
        },
        success: function (r) {
            if (r.r) {
                tribunes = r.data;
                if (!tribunes.length) {
                    $('#tribunes').hide();
                    $('#stadiumContainer').hide();
                    $('#stadiumLabel').hide();
                    Swal.fire("Advertencia", 'No existen sectores configurados con precio para el evento (' + activeMatchEvent.name + ').', "warning");
                    return;
                }
                for (let i = 0; i < tribunes.length; i++) {
                    zones = $('[alt="' + tribunes[i].alias);
                    if (zones.length) {
                        for (let j = 0; j < zones.length; j++) {
                            elClone = zones[j].cloneNode(true);
                            zones[j].parentNode.replaceChild(elClone, zones[j]);

                            // Agregar titulo del sector
                            snackbar = document.getElementById("snackbar");
                            snackbarTitle = document.getElementById("snackbar-title");
                            snackbarSubtitle = document.getElementById("snackbar-subtitle");
                            elClone.style.fill = 'D8D8D6';
                            if (tribunes[i].locked) {
                                elClone.style.fill = '#6A6A6A';
                                elClone.addEventListener('click', () => {
                                    Swal.fire("Advertencia", `El sector "${tribunes[i].name}" está bloqueado`, "warning");
                                });
                                elClone.addEventListener('mousemove', () => {
                                    snackbarTitle.textContent = tribunes[i].name;
                                    snackbarSubtitle.textContent = "El sector esta bloqueado";
                                    snackbar.className = "show";
                                });
                                elClone.addEventListener('mouseleave', () => {
                                    snackbarTitle.textContent = "";
                                    snackbarSubtitle.textContent = "";
                                    snackbar.className = "hide";
                                });
                            } else if (!tribunes[i].available_seats) {
                                elClone.style.fill = '#FF0000';
                                elClone.addEventListener('click', () => {
                                    Swal.fire("Advertencia", `El sector "${tribunes[i].name}" no tiene sillas disponibles`, "warning");
                                });
                                elClone.addEventListener('mousemove', () => {
                                    snackbarTitle.textContent = tribunes[i].name;
                                    snackbarSubtitle.textContent = "El sector no tiene sillas disponibles";
                                    snackbar.className = "show";
                                });
                                elClone.addEventListener('mouseleave', () => {
                                    snackbarTitle.textContent = "";
                                    snackbarSubtitle.textContent = "";
                                    snackbar.className = "hide";
                                });
                            } else {
                                elClone.addEventListener('click', () => { me.loadStadiumSeats(activeMatchEvent.id, tribunes[i].id, tribunes[i].name); });
                                elClone.addEventListener('mousemove', () => {
                                    snackbarTitle.textContent = tribunes[i].name;
                                    snackbarSubtitle.textContent = "Sillas disponibles: " + tribunes[i].available_seats;
                                    snackbar.className = "show";
                                });
                                elClone.addEventListener('mouseleave', () => {
                                    snackbarTitle.textContent = "";
                                    snackbarSubtitle.textContent = "";
                                    snackbar.className = "hide";
                                });
                            }
                        }
                    }
                }
                $('#tribunes').show();
                $('#stadiumContainer').show();
                $('#stadiumLabel').hide();
            } else {
                Swal.fire("Advertencia", r.m, "warning");
                $('#tribunes').hide();
                $('#stadiumContainer').hide();
                $('#stadiumLabel').show();
            }
        }
    });
}

function loadStadiumSeats(matchEventId, zoneId, zoneName) {
    validateZone = {
        id: zoneId,
        name: zoneName,
    };
    $.ajax({
        url: "/tickets/seats/" + zoneId + "/" + matchEventId,
        type: "GET",
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        success: function (r) {
            if (r.r) {
                $("#seatsContainer").empty();
                var seats = r.data;

                if (!seats.length) {
                    Swal.fire("Advertencia", 'No hay sillas disponibles para el sector (' + zoneName + ')', "warning");
                    return;
                }

                var group_seats = orderGroupBy(seats, "letter_id");
                if (group_seats) {
                    group_seats = group_seats.slice().reverse();
                }
                s3Url = $('#s3Url').val();
                time = new Date().getTime();
                for (let j = 0; j < group_seats.length; j++) {
                    var item = group_seats[j];
                    item.value = item.value.sort(function (a, b) {
                        return parseFloat(a.code) - parseFloat(b.code);
                    });
                    var list_seats = "";
                    for (let m = 0; m < item.value.length; m++) {
                        var seat = item.value[m];
                        let seatImage = "";
                        let openmodal = true;

                        if (!seat.ticket && !seat.ticket_user_block) {
                            seatImage = "available.png";
                        }

                        if (seat.ticket_user_block) {
                            openmodal = false;
                            seatImage = "not_available.png";
                        }
                        0
                        if (seat.ticket) {
                            openmodal = false;
                            seatImage = "not_available.png";
                        }

                        if (seat.presubscription) {
                            openmodal = false;
                            seatImage = "not_available.png";
                        }

                        if (seat.match_event_stage.length) {
                            openmodal = false;
                            seatImage = "not_available.png";
                        }

                        list_seats += `<div class="d-i-t text-center cursor" id="${seat.id}" onclick="modalSeat(this,'${window.btoa(
                            JSON.stringify(seat)
                        )}',${openmodal})">\
                            <img class="seat-image" src="${s3Url}/ticketing/seats/${seatImage}?_dc=${time}" alt="">\
                            <span>${seat.code}</span>\
                        </div>`;
                    }
                    var letter = item.value[0].letter.name;
                    var row = `<div class="row container_row"><span class="label_letter">${letter}</span>${list_seats}</div>`;
                    $("#seatsContainer").append(row);
                    $("#seats").show();
                    $("#seatsContainer").show();

                    //activeTribune.hide();
                    $('#tribunes').show();
                    $('#stadiumLabel').show();
                    $("#stadiumContainer").hide();
                    //$('#stadiumBreadcrumbs').show();
                    $('#tribuneBreadcrumbs').show();
                    $("#activeZoneLabel").html(capitalizeFirstLetter(zoneName));
                }
            } else {
                Swal.fire("Advertencia", r.m, "warning");
            }
        },
    });
}

function hideContainers() {
    $('#tribunes').hide();
    $("#occidental").hide();
    $("#oriental").hide();
    $("#norte").hide();
    $("#sur").hide();
    $("#stadiumContainer").hide();
    $("#stadiumLabel").hide();
    $("#stadiumBreadcrumbs").hide();
    $("#tribuneBreadcrumbs").hide();

    $("#seats").hide();
    $("#seatsContainer").hide();
}

function activateStadium(event = null) {
    if (ticketsToBuy.length)
        Swal.fire('Estás seguro de cambiar de tribuna, ya que esta acción eliminara las sillas seleccionadas?', {
            closeOnClickOutside: false,
            icon: "warning",
            buttons: {
                cancel: {
                    text: "No",
                    value: false,
                    visible: true,
                    className: "",
                    closeModal: true,
                },
                confirm: {
                    text: "Si, estoy seguro",
                    value: true,
                    visible: true,
                    className: "",
                    closeModal: true
                }
            },
        }).then((confirm) => {
            if (confirm) {
                ticketsToBuy = [];
                validateCheckout();
                loadTribunes(event);
            }
        });
    else
        loadTribunes(event);
}

function loadTribunes(event = null) {
    tribunes = [];
    resetSelectedTickets();
    hideContainers();
    if (event)
        activeMatchEvent = event;
    $("#email").prop('disabled', true);
    $("#confirm_email").prop('disabled', true);
    $("#first_name").prop('disabled', true);
    $("#last_name").prop('disabled', true);
    $("#phone").prop('disabled', true);
    $("#validate_button").prop('disabled', true);
    $.ajax({
        url: `/tickets/tribunesParent/${activeMatchEvent.event_id}`,
        type: "GET",
        contentType: "application/json",
        async: false,
        headers: {
            "Content-Type": "application/json",
        },
        success: function (r) {
            if (r.r) {
                tribunes = r.data;
            }
            $('#tribunes').show();
            $('#stadiumContainer').show();
            $('#stadiumLabel').hide();
        }
    });
}

function showTribune(tribune = null) {
    if (ticketsToBuy.length)
        Swal.fire('Estás seguro de cambiar de sector, ya que esta acción eliminara las sillas seleccionadas?', {
            closeOnClickOutside: false,
            icon: "warning",
            buttons: {
                cancel: {
                    text: "No",
                    value: false,
                    visible: true,
                    className: "",
                    closeModal: true,
                },
                confirm: {
                    text: "Si, estoy seguro",
                    value: true,
                    visible: true,
                    className: "",
                    closeModal: true
                }
            },
        }).then((confirm) => {
            if (confirm) {
                ticketsToBuy = [];
                validateCheckout();
                loadZones(tribune);
            }
        });
    else
        loadZones(tribune);
}

function loadZones(tribune = null) {
    zones = [];
    tribuneName = tribune ? tribune.title : $('area[alt="' + activeTribune[0].id + '"]')[0].title;
    if (tribune) {
        tribuneContainer = $("#" + tribuneName);
        activeTribune = tribuneContainer;
    } else {
        tribuneContainer = activeTribune;
    }

    validateTribune = tribunes.find(item => item.alias == tribuneName);
    if (validateTribune && validateTribune.match_event_stage.length) {
        Swal.fire("Advertencia", "Tribuna (" + capitalizeFirstLetter(tribuneName) + ") no disponible para este partido.", "warning");
        return;
    }

    $("#tribuneLabel").html(capitalizeFirstLetter(tribuneName));

    $.ajax({
        url: "/tickets/subZones/" + validateTribune.id + "/" + activeMatchEvent.event_id,
        type: "GET",
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        success: function (r) {
            if (r.r) {
                zones = r.data;
                hideContainers();
                tribuneContainer.show();
                $('#tribunes').show();
                $('#stadiumLabel').show();
                $("#stadiumContainer").hide();
            } else {
                Swal.fire("Advertencia", r.m, "warning");
            }
        },
    });
}

function showZone(zone) {
    validateZone = zones.find(item => item.alias == zone.title);
    if (validateZone && parseInt(validateZone.available_seats) <= 0) {
        Swal.fire("Advertencia", 'Ya se ha alcanzado el límite de aforo vendible para este sector (' + validateZone.name + ')', "warning");
        return;
    }

    $.ajax({
        url: "/tickets/seats/" + validateZone.id + "/" + activeMatchEvent.event_id,
        type: "GET",
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        success: function (r) {
            if (r.r) {
                $("#seatsContainer").empty();
                var seats = r.data;

                if (!seats.length) {
                    Swal.fire("Advertencia", 'No hay sillas disponibles para el sector (' + validateZone.name + ')', "warning");
                    return;
                }

                var group_seats = orderGroupBy(seats, "letter_id");
                if (group_seats) {
                    group_seats = group_seats.slice().reverse();
                }
                for (let j = 0; j < group_seats.length; j++) {
                    var item = group_seats[j];
                    item.value = item.value.sort(function (a, b) {
                        return parseFloat(a.code) - parseFloat(b.code);
                    });
                    var list_seats = "";
                    var s3Url = $('#s3Url').val();
                    for (let m = 0; m < item.value.length; m++) {
                        var seat = item.value[m];
                        let seatImage = "";
                        let openmodal = true;

                        if (!seat.ticket && !seat.ticket_user_block) {
                            seatImage = "available.png";
                        }

                        if (seat.ticket_user_block && seat.is_social_distancing) {
                            openmodal = false;
                            seatImage = "distancing.png";
                        }

                        if (seat.ticket_user_block && !seat.is_social_distancing) {
                            openmodal = false;
                            seatImage = "tempblock.png";
                        }

                        if (seat.ticket && seat.ticket_type_id == FREE_SALE) {
                            openmodal = false;
                            seatImage = "not_available.png";
                        }

                        if (seat.ticket && seat.ticket_type_id == SUBSCRIBER) {
                            openmodal = false;
                            seatImage = "suscription.png";
                        }

                        if (seat.ticket && seat.ticket_type_id == COMPLIMENTARY) {
                            openmodal = false;
                            seatImage = "courtesy.png";
                        }

                        if (seat.ticket && seat.ticket_type_id == CREDIT) {
                            openmodal = false;
                            seatImage = "not_available.png";
                        }

                        if (seat.match_event_stage.length) {
                            openmodal = false;
                            seatImage = "block.png";
                        }

                        list_seats += `<div class="d-i-t text-center cursor" id="${seat.id}" onclick="modalSeat(this,'${window.btoa(
                            JSON.stringify(seat)
                        )}',${openmodal})">\
                            <img class="seat-image" src="${s3Url}/ticketing/seats/${seatImage}" alt="">\
                            <span>${seat.code}</span>\
                        </div>`;
                    }
                    var letter = item.value[0].letter.name;
                    var row = `<div class="row container_row"><span class="label_letter">${letter}</span>${list_seats}</div>`;
                    $("#seatsContainer").append(row);
                    $("#seatsContainer").show();

                    activeTribune.hide();
                    $('#tribunes').show();
                    $('#stadiumLabel').show();
                    $("#stadiumContainer").hide();
                    $('#stadiumBreadcrumbs').show();
                    $('#tribuneBreadcrumbs').show();
                    $("#activeZoneLabel").html(capitalizeFirstLetter(validateZone.name));
                }
            } else {
                Swal.fire("Advertencia", r.m, "warning");
            }
        },
    });
}

function orderGroupBy(collection, property) {
    const groupedCollection = collection.reduce((previous, current) => {
        if (!previous[current[property]]) {
            previous[current[property]] = [current];
        } else {
            previous[current[property]].push(current);
        }

        return previous;
    }, {});
    return Object.keys(groupedCollection).map((key) => ({
        key,
        value: groupedCollection[key],
    }));
}

var formatter = new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
});
var current_e;
function modalSeat(e, seat, openmodal) {
    localStorage.removeItem("current_seat");
    current_e = e;
    seat = JSON.parse(window.atob(seat));
    var is_add_seat = ticketsToBuy.find((item) => item.seat.id == seat.id);
    if (is_add_seat) {
        const indexTicket = (item) => item.seat.id == seat.id;
        let index = ticketsToBuy.findIndex(indexTicket);
        if (index >= 0) {
            removeSeatListBuy(index, $(e));
        }
    } else {
        if (openmodal) {
            document.getElementById("form_sell_seat").reset();
            $("#seat_letter").val(seat.letter.name);
            $("#seat_code").val(seat.code);
            $.ajax({
                url: "/tickets/price/" + seat.zone_id + "/" + activeMatchEvent.event_id,
                type: "GET",
                contentType: "application/json",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                        "content"
                    ),
                    "Content-Type": "application/json",
                },
                success: function (r) {
                    if (r.r) {
                        var zonePrice = r.data;
                        if (zonePrice) {
                            localStorage.setItem("current_seat", JSON.stringify(seat));
                            localStorage.setItem("current_price", JSON.stringify(zonePrice));

                            $(".modal-body #price").val(
                                formatter.format(zonePrice.price)
                            );

                            $(".modal-body #container_service").hide();
                            if (zonePrice.service_charge) {
                                serviceCharge = typeof zonePrice.service_charge === 'string' && zonePrice.service_charge.includes('%') ? (parseFloat(zonePrice.service_charge) / 100) * zonePrice.price : zonePrice.service_charge;
                                $(".modal-body #service").val(formatter.format(serviceCharge));
                                $(".modal-body #container_service").show();
                            }
                            $(e).addClass("bg-seat-selected");
                            $("#modal_sell_seat").modal("show");
                            return;
                        }
                    }
                    Swal.fire("Advertencia", r.m ? r.m : "¡La zona seleccionada no tiene precios asignados para el evento!", "warning");
                },
            });
        }
    }
}

var ticketsToBuy = [];
function addSeat(presuscription = null) {
    if (validateAddSeat(/*ticket_type_id, presuscription*/)) {
        let seat = JSON.parse(localStorage.getItem("current_seat"));
        let zonePrice = JSON.parse(localStorage.getItem("current_price"));
        ticketsToBuy.push({
            seat: seat,
            match_event_id: activeMatchEvent.event_id,
            ticket_type_id: 1,
            match_event_price: zonePrice,
            dataTicket: null,
            service_charge: zonePrice.service_charge,
        });
        validateCheckout();
        $("#modal_sell_seat").modal("toggle");
    }
}

function validateCheckout() {
    html = ``;
    if (ticketsToBuy.length)
        html = `
            <div class="row" id="checkout-title">
                <div class="col-md-1 col-1">
                    <h5> </h5>
                </div>
                <div class="col-md-2 col-2 text-center">
                    <h5>Sector</h5>
                </div>
                <div class="col-md-3 col-3 text-center">
                    <h5>Letra</h5>
                </div>
                <div class="col-md-3 col-3 text-center">
                    <h5>Código</h5>
                </div>
                <div class="col-md-3 col-3 text-end">
                    <h5>Precio</h5>
                </div>
            </div>
        `;

    subTotal = 0;
    serviceTotal = 0;
    globalTotal = 0;
    ticketsToBuy.forEach(function (element) {
        seatLetter = element.seat.letter.name;
        seatCode = element.seat.code;
        total = element.match_event_price.price ? element.match_event_price.price : 0;
        subTotal += total;
        serviceCharge = 0;
        if (element.service_charge) {
            serviceCharge = typeof element.service_charge === 'string' && element.service_charge.includes('%') ? (parseFloat(element.service_charge) / 100) * total : element.service_charge;
        }
        serviceTotal += serviceCharge;
        globalTotal = subTotal + serviceTotal;
        html += `
            <hr class="rounded">
            <div class="row">
                <div class="col-md-1 col-1" style="display: flex; flex-flow: row;">
                    <img class="icon-remove-sign" src="/img/removeSeat.png" onclick="validateRemoveSeatListBuy(` + element.seat.id + `);">
                </div>
                <div class="col-md-2 col-2 text-center">
                    <h5>` + validateZone.name + `</h5>
                </div>
                <div class="col-md-3 col-3 text-center">
                    <h5>` + seatLetter + `</h5>
                </div>
                <div class="col-md-3 col-3 text-center">
                    <h5>` + seatCode + `</h5>
                </div>
                <div class="col-md-3 col-3 text-end">
                    <h5 class="currency">` + total + `</h5>
                </div>
            </div>
        `;
    });

    $("#checkout-body").html(html);
    $("#subtotal").html(subTotal);
    $("#service-total").html(serviceTotal);
    $("#total").html(globalTotal);

    if (ticketsToBuy.length > 0) {
        $('#buy-btn').show();
    } else {
        $('#buy-btn').hide();
    }
    setCurrencyFormat();
    $("html, body").animate({ scrollTop: $(document).height() }, 500);
}

function validateAddSeat(ticket_type_id, presuscription) {
    /*if (!ticket_type_id || ticket_type_id == 0) {
        Swal.fire("Advertencia", "¡Debes seleccionar tipo de boleta!", "warning");
        return;
    }

    if (presuscription && ticket_type_id == FREE_SALE) {
        Swal.fire("Advertencia", "Por el momento solo está habilitada la venta de abonos.", "warning");
        return;
    }

    if (ticket_type_id == FREE_SALE && ticketsToBuy.filter(ticket => ticket.ticket_type_id == SUBSCRIBER).length) {
        Swal.fire("Advertencia", "Solo puedes agregar boletas tipo Abonado en esta transacción.", "warning");
        return;
    }

    if (ticket_type_id == SUBSCRIBER && ticketsToBuy.filter(ticket => ticket.ticket_type_id == FREE_SALE).length) {
        Swal.fire("Advertencia", "Solo puedes agregar boletas tipo Venta libre en esta transacción.", "warning");
        return;
    }*/

    return true;
}

function removeSeatListBuy(index, seatContainer) {
    Swal.fire('Estás seguro de eliminar la silla?', {
        closeOnClickOutside: false,
        icon: "warning",
        buttons: {
            cancel: {
                text: "No",
                value: false,
                visible: true,
                className: "",
                closeModal: true,
            },
            confirm: {
                text: "Si, estoy seguro",
                value: true,
                visible: true,
                className: "",
                closeModal: true
            }
        },
    }).then((confirm) => {
        if (confirm) {
            seatContainer.removeClass('bg-seat-selected');
            if (ticketsToBuy && ticketsToBuy.length) {
                ticketsToBuy.splice(index, 1);
            }
            validateCheckout();
        }
    });
}

function tribunaHtml(tribuneJson, iconColor) {
    const price = tribuneJson.apply_coupon_type == 'special_price' ? tribuneJson.special_price : tribuneJson.price;
    const availableTickets = Object.keys(userTribuneStatus.available_tickets).length > 0 ? userTribuneStatus.available_tickets[tribuneJson.id] : tribuneJson.maximum_number_ballots;
    const arrayOfBallots = Array.from({ length: availableTickets + 1 }, (_, i) => i);
    return `
        <div id="amount-cupon-${tribuneJson.id}">
            <div class="row">
                <div class="col-md-7 col-7">
                    <h5>${tribuneJson.zone}</h5>
                </div>
                <div class="col-md-3 col-3 text-center">
                    <h5 class="currency">\$ ${price}</h5>
                </div>
                <div class="col-md-2 col-2 text-center">
                    <select style="font-size: 16px; min-width: 40px;" id="select-${tribuneJson.id}"
                        class="ticket-select"
                        onchange="onchangeSelect(this,${JSON.stringify(tribuneJson).replace(/"/g, "&quot;",)},'${iconColor}');">
                        ${arrayOfBallots.map((ballot) => `<option value="${ballot}">${ballot}</option>`)}
                    </select>
                </div>
            </div>
            <hr class="rounded">
        </div>
        `;
}

function handleCuponQuery(matchEventIdAuxi, iconColor) {
    var couponValue = $('#additional-input').val();
    $("#alert-cupon").hide();
    if (!couponValue) {
        return;
    }
    $.ajax({
        url: '/procesar-cupon/' + couponValue + '/' + 'yes' + '/' + matchEventIdAuxi,
        type: 'GET',
        success: function (response) {
            resetSelectedTickets();
            const tribunesContainerCoupon = $('#tribunes-container-coupon');
            if (response) {
                let unavailableTickets = false;
                response.forEach(function (tribunaJson) {
                    if (!Object.keys(userTribuneStatus.available_tickets).length || userTribuneStatus.available_tickets[tribunaJson.id] > 0) {
                        tribunesContainerCoupon.append(tribunaHtml(tribunaJson, iconColor));
                        $(`#amount-${tribunaJson.id}`).hide();
                    } else {
                        unavailableTickets = true;
                    }
                });
                if (unavailableTickets) {
                    $("#alert-cupon-unavailable").show();
                    setTimeout(function () {
                        $("#alert-cupon-unavailable").hide();
                    }, 3000);
                }
                if (response.length) {
                    $("#success-cupon").show();
                    setTimeout(function () {
                        $("#success-cupon").hide();
                    }, 3000);
                    $("#additional-input").val(couponValue);
                    if (!unavailableTickets) {
                        $("#additional-input").prop("disabled", true);
                        $("#aplicar-cupon-btn").prop("disabled", true);
                    }
                } else {
                    $("#alert-cupon").show();
                    setTimeout(function () {
                        $("#alert-cupon").hide();
                    }, 3000);
                }
            }

        },
        error: function (error) {
            $("#alert-cupon").show();
        }
    });
}

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function validateRemoveSeatListBuy(seatId) {
    const indexTicket = (item) => item.seat.id == seatId;
    let index = ticketsToBuy.findIndex(indexTicket);
    if (index >= 0) {
        removeSeatListBuy(index, $(`#${seatId}`));
    }
}

const isMobile = {
    Android: function () {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function () {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function () {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function () {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function () {
        return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
    },
    any: function () {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};
function resizePage() {
    if (isMobile.any()) {
        let childs = document.getElementsByClassName('col-md-6 col-12 p-xs-0');
        let height = 0;
        for (let i = 0; i < childs.length; i++) {
            height += childs[i].offsetHeight;
        }
        document.body.style.height = height + 'px';
    }
}