<script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-firestore.js"></script>

<script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
    apiKey: "AIzaSyAKXXqrLSuNLjxw18LZOJGuvPnfm5T08b8",
    authDomain: "beegoup-160ea.firebaseapp.com",
    projectId: "beegoup-160ea",
    storageBucket: "beegoup-160ea.appspot.com",
    messagingSenderId: "700764845607",
    appId: "1:700764845607:web:5a97bd8987de0b7a66c002"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
    var db = firebase.firestore();
</script>
<style>
    .message {
        padding: 5px !important;
        border-radius: 5px !important;
        margin-bottom: 4px !important;
        vertical-align: text-bottom !important;
        position:relative !important;
    }

    .other-message {
        background: #adacb2ff;
        color: black;
    }

    .my-message {
        background: #a21858ff;
        color: aliceblue;
    }

    .time {
        color: aliceblue;
        float: right;
        font-size: small;
    }

    .header1 {
        background: #b2003eff;
        padding: -20;
        position: sticky;    
        top: 0;
        left: 0;
        width: 100%;
        z-index: 20;
        text-align: center;
        color: #ffffff;
    }

    .footer {
        background: transparent;
        /* color: #ffffff; */
        font-size: 13px;
        bottom: 0px;
        position: sticky;
        left: 0px;
        width: 100%;
        z-index: 10;
        /*  border-top: 3px solid #ffffff; */
    }

    .footer2 {
        position: sticky;
        bottom: 0px;
    }

    .size-t {
        font-size: 26px !important;
    }

    .size-22 {
        font-size: 22px !important;
    }

    .size-12 {
        font-size: 12px;
    }

    .size-16 {
        font-size: 16px;
    }
    .size-10 {
        font-size: 10px;
    }

    .color-primary {
        color: #fafafa;
        background: #b2003eff;
    }

    .color-p {
        color: #b2003eff !important;
    }
    .color-s {
        color: #adacb2ff !important;
    }
</style>
<script>
    var input = document.getElementById("text");
    /* input.addEventListener("keyup", function (event) {
      if (event.keyCode === 13) {
        event.preventDefault();
        document.getElementById("btn_send").click();
      }
    }); */
    var myName = '';


    var nameGroup = '';


    function init() {
        myName = "<?php echo $data['nombre'] . ' ' . $data['apellidos']; ?>";
        nameGroup = "<?php echo $data['equipo']; ?>";
        messages = [];




        db.collection('chat').where('id', '==', nameGroup).onSnapshot((snap1) => {

            messages = null;
            snap1.forEach(child => {
                messages = {
                    id: child.id,
                    data: child.data()
                };
            });

            if (messages == null) {
                db.collection("chat").add({
                    id: nameGroup,
                    messages: []
                });
            } else {
                var html = "";
                inicio = `
                    <div >
                        <div class="text-center" style="margin-top: 10%; ">
                            <h4 class="size-12" >Bienvenido al chat grupal del equipo ` + nameGroup + `</h4>
                        </div>
                    </div>
                    `;
                html += inicio;
                messages.data.messages.forEach(msj => {
                    var fecha = (new Date(msj.date));
                    var fechaOld = (new Date(msj.dateOld));
                    var item = "";
                    var item1 = "";
                    if (fecha.toDateString() != fechaOld.toDateString()) {
                        item1 = `
                        
                        <div class="row">
                <div class="col-12">
                  <p class="text-center color-p size-10">` + fecha.toLocaleDateString() + `</p>
                </div>
              </div>
              `;

                    }

                    if (msj.name != myName) {
                        item +=
                            `
                <div class="col-9 message other-message">
                  <b class="color-p size-12">` + msj.name + `</b><br>
                  <span class=" size-12">` + msj.content + `</span>
                  <div class="time size-10" text-right>
                    ` + fecha.toLocaleTimeString() + `
                  </div>
                </div>
                <div class="col-3"></div>`;
                    } else {
                        item +=
                            `
                <div class="col-3"></div>
                <div class="col-9 message my-message">
                  <b class="color-s size-12">T&uacute;</b><br>
                  <span class="size-12">` + msj.content + `</span>
                  <div class="time size-10" text-right>
                    ` + fecha.toLocaleTimeString() + `
                  </div>
                </div>`;
                    }
                    var msjHtml =
                        `
        <div class="row">
      <div class="col-12">
      
        ` + item1 + `

        <div class="row">
          ` + item + `

        </div>
      </div>
    </div>
        `;

                    html += msjHtml;
                });
                document.getElementById('titulo').innerText = "Equipo " + nameGroup;
                document.getElementById('contenedor').innerHTML = html;
                setTimeout(() => {
                    console.log(document.getElementById('contenedor'));
                    //document.getElementById('contenedor').animate({ scrollTop: 3000 }, 400);
                    document.getElementById('main').scrollIntoView(0, document.getElementById('main').scrollHeight);
                }, 300);

            }


        });

    }

    function sendMsj() {
        var text = document.getElementById('text').value;
        if (text != '') {
            var date = new Date().toISOString();
            var s = this.messages.data.messages.length;
            db.collection('chat').doc(messages.id).update({
                messages: firebase.firestore.FieldValue.arrayUnion({
                    content: text,
                    type: 'text',
                    name: myName,
                    date,
                    dateOld: s === 0 ? null : messages.data.messages[s - 1].date,
                })
            }).then(() => {
                document.getElementById('text').value = '';
                setTimeout(() => {
                    document.getElementById('main').scrollIntoView(0, document.getElementById('main').scrollHeight);
                }, 300);
            })
        }
    }
    init();
</script>

<div id="main">
    <div class="header1">
        <h1 class="size-16" id="titulo"></h1>
    </div>
    <div id="contenedor"></div>


    <div class="footer2" id="footer">
        <div class="input-group">
            <input class="form-control" style="font-size: 12px;" type="text" placeholder="Escribe el mensaje aquí ..." id="text" value="">
            <button class="btn color-primary" style="font-size: 12px;"  id="btn_send" onclick="sendMsj()">Enviar</button>
        </div>

    </div>
</div>