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/teamdemo.sports-crowd.com/public/js/tickets.js
activeMatchEvent = null;
subTotal = 0;
serviceTotal = 0;
globalTotal = 0;
const FREE_SALE = 1;
const SUBSCRIBER = 2;
const COMPLIMENTARY = 3;
const CREDIT = 4;

$(document).ready(function () {
    var input = document.getElementById("document_search");
    input.addEventListener("keyup", function (event) {
        if (event.keyCode === 13) {
            event.preventDefault();
            searchUser();
        }
    });

    $("#event_id").on("change", function () {
        if (this.value != "0") {
            let event = JSON.parse(this.value);
            loadStadiumZones(event).then(() => {
                $("#event_name").html(event.name);
                $('#stadiumBreadcrumbs').show();
                $("#container_event").hide();
            }).catch(e => {
                console.log('error loadStadiumZones :>> ', e);
            });
        }
    });

    $("#ticket_type_id").on("change", function () {
        $("#container_price").hide();
        $("#container_suscription").hide();
        $("#container_service").hide();
        $("#container_service_suscription").hide();

        let type = parseInt(this.value);
        if (type == FREE_SALE) {
            $("#container_price").show();
            if ($("#service").val()) {
                $("#container_service").show();
            }
        } else if (type == SUBSCRIBER) {
            $("#container_suscription").show();
            if ($("#service_suscription").val()) {
                $("#container_service_suscription").show();
            }
        }
    });

    $("#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 formatter = new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 0,
});

function activeEvent() {
    $("#container_event").show();
    $("#event_id").val(0);
    $("#event_id").change();
    $("#stadium").html('');
    $("#stadiumBreadcrumbs").hide();
    hideContainers();
    localStorage.clear();
    ticketsToBuy = [];
}

function showTribune(tribune) {
    let tribunes = document.querySelector('#stadiumContainer');
    tribunes = JSON.parse(tribunes.dataset.tribune);
    // const activeTribune = tribunes.find(item => item.id == zone_id && !item.match_event_stage.length);
    const activeTribune = tribunes.find(item => item.alias == tribune.title && !item.match_event_stage.length);
    if (activeTribune) {
        $("#container_image_seat").hide();
        $("#stadiumContainer").hide();
        $("#" + activeTribune.alias).show();
        // $("#container_" + activeTribune.id).show();
        $("#tribuneBreadcrumbs").show();
        $("#stadiumBreadcrumbs a").html(Lang.get("messagesClient.tickets.title_11") + ' - ' + activeTribune.name);
        $("#current_zone").val(activeTribune.alias);
        localStorage.setItem("name_zone", activeTribune.name);
        $("#div_footer").hide();
        getSubZones(activeTribune.id);
    } else {
        Swal.fire("Advertencia", "Tribuna (" + capitalizeFirstLetter(tribune.title) + ") no disponible para este partido.", "warning");
        return;
    }
}

function activeZone() {
    $("#container_image_seat").hide();
    var activeTribune = $("#current_zone").val();
    $("#stadiumContainer").show();
    $("#" + activeTribune).hide();
    $("#body_seat").hide();
    $("#tribuneBreadcrumbs").hide();
    $("#breadcrumbs_subzone").hide();
    $("#stadiumBreadcrumbs a").html(Lang.get("messagesClient.tickets.title_11"));
    $("#tribuneBreadcrumbs a").html(Lang.get("messagesClient.tickets.title_12"));
    $("#div_footer").hide();
    ticketsToBuy = [];
}

function activeSubzone() {
    $("#container_image_seat").hide();
    var activeTribune = $("#current_zone").val();
    $("#stadiumContainer").hide();
    $("#breadcrumbs_subzone").hide();
    $("#tribuneBreadcrumbs a").html(Lang.get("messagesClient.tickets.title_12"));
    $("#body_seat").hide();
    $("#" + activeTribune).show();
    $("#div_footer").hide();
    ticketsToBuy = [];
}

function activeSubzone2() {
    var activeTribune = $("#current_zone").val();
    $("#stadiumContainer").hide();
    $("#" + activeTribune).hide();
    $("#body_seat").show();
}

function getSubZones(zone_id) {
    var event_id = activeMatchEvent.id;
    $.ajax({
        url: "/tickets/subZones/" + zone_id + "/" + event_id,
        type: "GET",
        contentType: "application/json",
        headers: {
            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            "Content-Type": "application/json",
        },
        success: function (r) {
            const sub_zones = r.data;
            window.subZones = sub_zones;
            sub_zones.forEach(element => {
                e = $('area[alt="' + element.alias);
                if (e[0]) {
                    e[0].setAttribute("title", element.name + "\nDisponibles: " + element.available_seats);
                }
            });
        },
    });
}

function showZone(zone = null, subzone_id = null, name_subzone) {
    if (zone)
        subZone = window.subZones.find(item => item.alias == zone.alt);
    else
        subZone = window.subZones.find(item => item.id == subzone_id);

    if (subZone && parseInt(subZone.available_seats) <= 0) {
        Swal.fire("Advertencia", 'Ya se ha alcanzado el limite de aforo vendible para esta localidad', "warning");
        return;
    }
    var event_id = activeMatchEvent.id;
    $.ajax({
        url: "/tickets/seats/" + subZone.id + "/" + 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 activeTribune = $("#current_zone").val();
                $("#stadiumContainer").hide();
                $("#" + activeTribune).hide();

                $("#current_subzone").val(subZone.id);
                $("#breadcrumbs_subzone").show();
                $("#tribuneBreadcrumbs a").html(Lang.get("messagesClient.tickets.title_12") + ' - ' + subZone.name);
                $("#container_image_seat").show();
                localStorage.setItem("name_subzone", subZone.name);

                $("#body_seat").show();
                $("#body_seat").empty();
                var seats = r.data;

                var group_seats = orderGroupBy(seats, "letter_id");
                if (group_seats) {
                    group_seats = group_seats.slice().reverse();
                    $("#div_footer").show();
                }
                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 seat_image = "";
                        let openmodal = true;

                        if (!seat.ticket && !seat.ticket_user_block) {
                            seat_image = "seat_available.png";
                        }

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

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

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

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

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

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

                        if (seat.match_event_stage.length) {
                            openmodal = false;
                            seat_image = "seat_block.png";
                        }

                        list_seats += `<div class="d-i-t text-center cursor" onclick="modalSeat(this,'${window.btoa(
                            JSON.stringify(seat)
                        )}',${openmodal})">\
                            <img class="image_seat" src="img/${seat_image}" 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>`;
                    $("#body_seat").append(row);
                }
            } 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],
    }));
}

function removeSeatListBuy(index) {
    if (ticketsToBuy && ticketsToBuy.length) {
        ticketsToBuy.splice(index, 1);
    }
}

var current_e;
function modalSeat(e, seat, openmodal) {
    localStorage.removeItem("current_seat");
    $(e).removeClass("bg-seat-selected");
    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 current_list = (item) => item.seat.id == seat.id;
        let index = ticketsToBuy.findIndex(current_list);
        if (index >= 0) {
            $(e).removeClass("bg-seat-selected");
            removeSeatListBuy(index);
        }
    } else {
        if (openmodal) {
            $("#container_data_user").hide();
            $("#container_price").hide();
            $("#container_suscription").hide();
            $("#container_service").hide();
            $("#container_service_suscription").hide();
            $("#user_id").val("0");
            document.getElementById("form_sell_seat").reset();
            $("#seat_id").val(seat.id);
            $.ajax({
                url: "/tickets/price/" + seat.zone_id + "/" + activeMatchEvent.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_sell_seat").modal("show");
                            $(".modal-body #price").val(formatter.format(zonePrice.price));
                            $(".modal-body #price_suscription").val(formatter.format(zonePrice.price_suscription));
                            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));
                            }
                            if (zonePrice.service_charge_subscriber) {
                                serviceChargeSuscription = typeof zonePrice.service_charge_subscriber === 'string' && zonePrice.service_charge_subscriber.includes('%') ? (parseFloat(zonePrice.service_charge_subscriber) / 100) * zonePrice.price_suscription : zonePrice.service_charge_subscriber;
                                $(".modal-body #service_suscription").val(formatter.format(serviceChargeSuscription));
                            }
                            $(e).addClass("bg-seat-selected");
                        } else {
                            Swal.fire("Advertencia", "¡La zona seleccionada no tiene precios asignados para el evento!", "warning");
                        }
                    }
                },
            });
        }
    }
}

function searchUser() {
    var document_search = $("#document_search").val();
    document.getElementById("form_sell_checkout").reset();
    $("#user_id").val("0");
    $("#first_name").val("");
    $("#last_name").val("");
    $("#phone").val("");
    $("#email_user").val("");
    if (document_search && document_search != "") {
        let ticket_type_id = $("#form_sell_seat select[name='ticket_type_id']").val();
        $.ajax({
            url: "/tickets/user/" + document_search,
            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) {
                    $("#container_data_user").show();
                    $("#document").val(document_search);
                    var current_user = r.data;
                    if (current_user) {
                        $("#user_id").val(current_user.id);
                        $("#first_name").val(current_user.first_name);
                        $("#last_name").val(current_user.last_name);
                        $("#phone").val(current_user.phone);
                        $("#email_user").val(current_user.email);

                        $("#button_edi_user").prop("disabled", false);
                    } else {
                        $("#button_edi_user").prop("disabled", true);
                    }
                }
            },
        });
    } else {
        Swal.fire("Advertencia", "¡Debes ingresar un documento valido!", "warning");
    }
}

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 (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;
}

var ticketsToBuy = [];
function addSeat(presuscription) {
    var ticket_type_id = parseInt($("#form_sell_seat select[name='ticket_type_id']").val());
    var event_id = activeMatchEvent.id;

    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: event_id,
            ticket_type_id,
            match_event_price: zonePrice,
            zone_name: (seat.zone && seat.zone.zone) ? (seat.zone.name === seat.zone.zone.name ? seat.zone.name : seat.zone.name + " - " + seat.zone.zone.name) : '',
            dataTicket: null,
            service_charge: ticket_type_id == FREE_SALE ? zonePrice.service_charge : zonePrice.service_charge_subscriber,
        });
        validateCheckout();
        $("#modal_sell_seat").modal("toggle");
    }
}

function validateCheckout(goEnd = true) {
    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;
        if (element.ticket_type_id == FREE_SALE) {
            total = element.match_event_price.price ? element.match_event_price.price : 0;
        } else {
            total = element.match_event_price.price_suscription ? element.match_event_price.price_suscription : 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();
    $("#checkout").show();
    $("#div_footer").show();

    if (goEnd) {
        $("html, body").animate({ scrollTop: $(document).height() }, 500);
    } else {
        $("html, body").animate({ scrollTop: 0 }, 500);
    }
}

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

function currencyMask(data) {
    const formatter = new Intl.NumberFormat('es-CO', {
        style: 'currency',
        currency: 'COP',
        minimumFractionDigits: 0,
        maximumFractionDigits: 0,
    });
    return formatter.format(data);
}

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

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 create(origin) {
    var user_id = $("#form_sell_checkout input[name='user_id']").val();
    var first_name = $("#form_sell_checkout input[name='first_name']").val();
    var last_name = $("#form_sell_checkout input[name='last_name']").val();
    var document = $("#form_sell_checkout input[name='document']").val();
    var phone = $("#form_sell_checkout input[name='phone']").val();
    var email = $("#form_sell_checkout input[name='email_user']").val();

    if (user_id == "") {
        Swal.fire("Advertencia", "¡Debes ingresar un usuario!", "warning");
        return;
    }

    if (first_name == "") {
        Swal.fire("Advertencia", "¡Debes ingresar nombres del usuario!", "warning");
        return;
    }

    if (last_name == "") {
        Swal.fire("Advertencia", "¡Debes ingresar apellidos del usuario!", "warning");
        return;
    }

    if (document == "") {
        Swal.fire("Advertencia", "¡Debes ingresar documento del usuario!", "warning");
        return;
    }

    if (phone == "") {
        Swal.fire("Advertencia", "¡Debes ingresar telefono del usuario!", "warning");
        return;
    }

    if (email == "") {
        Swal.fire("Advertencia", "¡Debes ingresar correo electrónico del usuario!", "warning");
        return;
    }

    if (ticketsToBuy[0].ticket_type_id == SUBSCRIBER) {
        let no_data_tickets = ticketsToBuy.filter(ticket => ticket.dataTicket == null).length;
        if (no_data_tickets > 0) {
            Swal.fire("Advertencia", "Debes indicar información de cada abonado, haz clic sobre él y diligencia la información.", "warning");
            return;
        }
    }

    $("#btn-create").hide();
    $("#spinnerButton").show();

    var info = {
        user_id,
        first_name,
        last_name,
        document,
        phone,
        email,
        tickets: ticketsToBuy,
        type_process: "block",
        subtotal: subTotal,
        serviceCharge: serviceTotal,
        amount: globalTotal,
        ticket_type_id: ticketsToBuy[0].ticket_type_id,
        season_id: $('#event_id').find('option:selected').attr('season_id'),
    };

    swal("¿Desea realizar la venta de esta(s) boleta(s)?", {
        buttons: {
            cancel: "No",
            Ok: true,
        },
    }).then((val) => {
        if (val == "Ok") {
            $.ajax({
                url: "/tickets/createBlock/" + origin,
                type: "POST",
                contentType: "application/json",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                        "content"
                    ),
                    "Content-Type": "application/json",
                },
                data: JSON.stringify(info),
                success: function (r) {
                    $("#btn-create").show();
                    $("#spinnerButton").hide();
                    if (r.r) {
                        swal(r.m, {
                            icon: "success",
                            buttons: {
                                Ok: true,
                            },
                        }).then((val) => {
                            if (val == "Ok") {
                                $(location).attr("href", window.location.pathname);
                            }
                        });
                    } else {
                        Swal.fire("Error", r.m, "error");
                    }
                },
                error: function (e) {
                    Swal.fire("Error", "¡Hubo un Error al crear!", "error");
                    $("#btn-create").show();
                    $("#spinnerButton").hide();
                },
            });
        } else {
            $("#btn-create").show();
            $("#spinnerButton").hide();
        }
    });
}

function getFormData(form_id) {
    var elements = document.getElementById(form_id).elements;
    var obj = {};
    for (var i = 0; i < elements.length; i++) {
        var item = elements.item(i);
        obj[item.name] = item.value;
    }

    return JSON.stringify(obj);
}

var listPropertiesFormDataAbonado = ["first_name", "last_name", "document", "phone", "email_user"];
function defaultUser(index) {
    let dataUser = JSON.parse(getFormData("form_sell_checkout"));
    let properties = Object.getOwnPropertyNames(dataUser);
    if (document.querySelector(`#order_check${index}`).checked) {
        let dataTicket = { checkedCtrl: true };
        if (!dataUser.document || dataUser.document == "") {
            Swal.fire("Advertencia", "¡Debes ingresar primero el usuario!", "warning");
            $(`#order_check${index}`).prop('checked', false);
            return
        }
        $(`#button_add_abonado${index}`).prop("disabled", true);
        properties.forEach(item => {
            if (listPropertiesFormDataAbonado.indexOf(item) !== -1) {
                dataTicket[item] = dataUser[item];
                $(`#${item}${index}`).val(dataUser[item]);
                $(`#${item}${index}`).prop("disabled", true);
            }
        });
        ticketsToBuy[index].dataTicket = dataTicket;
    } else {
        $(`#button_add_abonado${index}`).prop("disabled", false);
        properties.forEach(item => {
            if (listPropertiesFormDataAbonado.indexOf(item) !== -1) {
                $(`#${item}${index}`).val("");
                $(`#${item}${index}`).prop("disabled", false);
            }
        });
        ticketsToBuy[index].dataTicket = null;
    }
}

function assingAbonado(index) {
    let dataUser = JSON.parse(getFormData("form_sell_checkout"));
    let properties = Object.getOwnPropertyNames(dataUser);
    let dataTicket = { checkedCtrl: false };
    let state = true;
    properties.forEach(item => {
        if (listPropertiesFormDataAbonado.indexOf(item) !== -1) {
            let value = $(`#${item}${index}`).val();
            if (!value || value == "") {
                if (item == "first_name") {
                    state = false;
                    Swal.fire("Advertencia", "¡Debes ingresar nombres del usuario!", "warning");
                    return;
                }

                if (item == "last_name") {
                    state = false;
                    Swal.fire("Advertencia", "¡Debes ingresar apellidos del usuario!", "warning");
                    return;
                }

                if (item == "document") {
                    state = false;
                    Swal.fire("Advertencia", "¡Debes ingresar documento del usuario!", "warning");
                    return;
                }

                if (item == "phone") {
                    state = false;
                    Swal.fire("Advertencia", "¡Debes ingresar telefono del usuario!", "warning");
                    return;
                }

                if (item == "email_user") {
                    state = false;
                    Swal.fire("Advertencia", "¡Debes ingresar correo electrónico del usuario!", "warning");
                    return;
                }
            }
            dataTicket[item] = value;
        }
    });
    if (state) {
        Swal.fire("Ok", "Se agregó exitosamente la información", "success");
    }
    ticketsToBuy[index].dataTicket = state ? dataTicket : null;
}

var total = 0;
function buyTickets() {
    if (ticketsToBuy && ticketsToBuy.length) {
        $("#modal_buy_tickets").modal("show");
        $("#list_tickets").empty();
        $("#accordionAbonos").empty();
        $("#add-tab").trigger("click");
        $("#container_data_user").hide();
        document.getElementById("form_sell_checkout").reset();
        var items = "";
        for (let i = 0; i < ticketsToBuy.length; i++) {
            var t = ticketsToBuy[i];
            var price = 0;

            if (t.ticket_type_id == FREE_SALE) {
                price = t.match_event_price.price;
            } else if (t.ticket_type_id == SUBSCRIBER) {
                price = t.match_event_price.price_suscription;
            }

            if (t.ticket_type_id != 2) {
                items =
                    items +
                    `<span class="list-group-item list-group-item-action">
                        <div class="d-flex w-100 justify-content-between">
                            <h5 class="mb-1">${validateZone.name}</h5>
                            <small class="small_price">${formatter.format(
                        price
                    )}</small>
                        </div>
                        <p class="mb-1">Silla: ${t.seat.letter.name}${t.seat.code}</p>
                    </span>`;
            } else {
                items = items + `<div class="panel panel-default">
                                    <div class="panel-heading pos-r" role="tab" id="heading${i}">
                                        <h4 class="panel-title">
                                            <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordionAbonos" href="#collapse${i}" aria-expanded="false" aria-controls="collapse${i}">
                                            ${t.zone_name} - ${t.seat.letter.name}${t.seat.code}
                                            </a>
                                            <small class="small_price_abono">${formatter.format(price)}</small>
                                        </h4>
                                    </div>
                                    <div id="collapse${i}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading${i}">
                                        <div class="panel-body container_form">
                                            <div class="containerCheckbox">
                                                <input type="checkbox" id="order_check${i}" onchange="defaultUser(${i})">
                                                <label for="order_check${i}">Asignar al mismo usuario</label>
                                            </div>
                                            <div>
                                                <div class="form-group m-b-10">
                                                    <div class="form-group col-md-6">
                                                        <label for="first_name${i}">${Lang.get("messagesClient.tickets.title_3")}</label>
                                                        <input type="text" id="first_name${i}" class="form-control" name="first_name${i}" required>
                                                    </div>
                                                    <div class="form-group col-md-6">
                                                        <label for="last_name${i}">${Lang.get("messagesClient.tickets.title_4")}</label>
                                                        <input type="text" id="last_name${i}" class="form-control" name="last_name${i}" required>
                                                    </div>
                                                </div>
                                                <div class="form-group m-b-10">
                                                    <div class="form-group col-md-6">
                                                        <label for="document${i}">${Lang.get("messagesClient.tickets.title_5")}</label>
                                                        <input type="text" id="document${i}" class="form-control" name="document${i}" required>
                                                    </div>
                                                    <div class="form-group col-md-6">
                                                        <label for="phone${i}">${Lang.get("messagesClient.tickets.title_6")}</label>
                                                        <input type="text" id="phone${i}" class="form-control" name="phone${i}" required>
                                                    </div>
                                                </div>
                                                <div class="form-group col-md-10">
                                                    <label for="email_user${i}">${Lang.get("messagesClient.tickets.title_7")}</label>
                                                    <input type="text" id="email_user${i}" class="form-control" name="email_user${i}" required>
                                                </div>

                                                <div class="form-group col-md-2">
                                                <label></label>
                                                    <button onClick="assingAbonado(${i})" type="button" class="btn btn-danger btnPlusDir pull-left" id="button_add_abonado${i}">
                                                        <i class="">${Lang.get("messagesClient.tickets.title_8")}</i>
                                                    </button>
                                                </div>
                                            </div>
                                            <br>
                                            <div>
                                                <h5 class="text-alert">Te recomendamos diligenciar los campos con la información de un usuario ya registrado en DIM Plus. Ten presente que las boletas quedarán cargadas a nombre de la persona que indiques y que en caso de que no tenga usuario en la app, realizaremos el registro automático de un usuario nuevo con los datos suministrados. Para ingresar a la aplicación y consultar las boletas deberás usar la opción 'Recuperar contraseña' en la pantalla de inicio de sesión.</h5>
                                            </div>
                                        </div>
                                    </div>
                                </div>`
            }
        }
        if (ticketsToBuy[0].ticket_type_id != 2) {
            $("#list_tickets").append(items);
        } else {
            $("#accordionAbonos").append(items);
        }
        $("#sub_total").html(`${formatter.format(subTotal)}`);
        $("#service_total").html(`${formatter.format(serviceTotal)}`);
        $("#total_price").html(`${formatter.format(globalTotal)}`);
    } else {
        Swal.fire("Advertencia", "¡Debes seleccionar al menos una silla!", "warning");
    }
}

function edit() {
    var document = $('input[name=document]').val();
    if (document) {
        var info = {
            user_id: $("#form_sell_checkout input[name='user_id']").val(),
            first_name: $("#form_sell_checkout input[name='first_name']").val(),
            last_name: $("#form_sell_checkout input[name='last_name']").val(),
            document: $("#form_sell_checkout input[name='document']").val(),
            phone: $("#form_sell_checkout input[name='phone']").val(),
            email: $("#form_sell_checkout input[name='email_user']").val(),
        };

        swal(Lang.get("messagesClient.tickets.tag_2"), {
            buttons: {
                cancel: "No",
                Ok: true,
            },
        }).then((val) => {
            if (val == "Ok") {
                $.ajax({
                    url: "/tickets/update",
                    type: "PUT",
                    contentType: "application/json",
                    headers: {
                        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                            "content"
                        ),
                        "Content-Type": "application/json",
                    },
                    data: JSON.stringify(info),
                    success: function (r) {
                        if (r.r) {
                            swal(Lang.get("messagesClient.tickets.tag_3"), {
                                icon: "success",
                                timer: 1700,
                                showConfirmButton: false,
                                buttons: false,
                            });
                        } else {
                            Swal.fire("Error", r.m, "error");
                            $("#button_edi_user").show();
                            $("#spinnerButton").hide();
                        }
                    },
                    error: function (e) {
                        Swal.fire("Error", Lang.get("messagesClient.tickets.tag_1"), "error");
                        $("#button_edi_user").show();
                        $("#spinnerButton").hide();
                    },
                });
            } else {
                $("#button_edi_user").show();
                $("#spinnerButton").hide();
            }
        });
    }
}

function loadStadiumZones(event = null) {
    hideContainers();
    if (event) {
        activeMatchEvent = event;
    }
    var me = this;
    return new Promise((resolve, reject) => {
        $.ajax({
            url: `/tickets/loadStadiumZones`,
            type: "GET",
            contentType: "application/json",
            async: false,
            headers: {
                "Content-Type": "application/json",
            },
            data: {
                'matchEventId': activeMatchEvent.id
            },
            success: function (r) {
                showStadiumMap(activeMatchEvent);
                if (r.r) {
                    tribunes = r.data;
                    if (!tribunes.length) {
                        $('#stadiumContainer').hide();
                        Swal.fire("Advertencia", 'No existen sectores configurados con precio para el evento (' + activeMatchEvent.name + ').', "warning");
                        reject();
                        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";
                                    });
                                }
                            }
                        }
                    }
                    $('#stadiumContainer').show();
                } else {
                    Swal.fire("Advertencia", r.m, "warning");
                    $('#stadiumContainer').hide();
                }
                resolve();
            },
            error: function (e) {
                reject();
                Swal.fire("Error", Lang.get("messagesClient.tickets.tag_1"), "error");
            },
        });
    });
}

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 && 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.presubscription) {
                            openmodal = false;
                            seatImage = "suscription.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}?_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();

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

function showStadiumMap(event) {
    $("#stadium").html(event.stadium);
}

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

function showActiveEvents(event = null) {
    if (ticketsToBuy.length)
        Swal.fire('Estás seguro de cambiar de partido, 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(false);
                activeEvent(event);
            }
        });
    else
        activeEvent(event);
}

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(false);
                loadStadiumZones(event);
            }
        });
    else
        loadStadiumZones(event);
}

function hideContainers() {
    $("#tribuneBreadcrumbs").hide();
    $("#stadiumContainer").hide();
    $("#seats").hide();
    $("#seatsContainer").hide();
    $("#checkout").hide();
    $("#div_footer").hide();
}