<template>
    <li class="nav-item dropdown">
        <a class="nav-link" data-toggle="dropdown" href="#" aria-expanded="true">
          <i class="far fa-bell"></i>
          <span  class="badge badge-danger navbar-badge">{{ notifications.length }}</span>
        </a>
        <div class="dropdown-menu dropdown-menu-xl dropdown-menu-right">
          <template  v-for="(not,index) in notifications">
            <a @click="markRead(not.id)" href="#" class="dropdown-item">
              <!-- Message Start -->
              <div class="media">
                <img :src="`/img/${not.sender.image}`" alt="User Avatar" class="img-size-50 mr-3 img-circle">
                <div class="media-body">
                  <h3 class="dropdown-item-title">
                    {{not.sender.name}}
                    <span  class="float-right text-sm text-muted"><i class="fas fa-star"></i></span>
                  </h3>
                  <p class="text-sm">{{not.message}}</p>
                  <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> {{ not.time }}</p>
                </div>
              </div>
              <!-- Message End -->
            </a>

            <div class="dropdown-divider"></div>
          </template>
          <a @click="markAllRead" href="#" class="dropdown-item dropdown-footer">{{$t('See All Messages')}}</a>
        </div>
      </li>

</template>

<script>
export default {
  props: [],
  data: function () {
    return {
      notifications: [],
      sound: true
    };
  },
  mounted() {
    this.loadData();
    this.listen();
  },
  methods: {
    listen(){
      Echo.private('users.'+this.$root.auth.id)
          .notification((notification) => {
              this.notifications.unshift(notification);
              if(this.sound){
               let audio = new Audio('/media/notification.mp3');
                  audio.play();
             }
       });
       if(this.$root.auth.office_id){
          Echo.private('offices.'+this.$root.auth.office_id)
          .notification((notification) => {
              this.notifications.unshift(notification);
              if(this.sound){
               let audio = new Audio('/media/notification.mp3');
                  audio.play();
             }
       });
       }
    },
    loadData() {
      axios.get("/notif").then((resp) => {
       this.notifications = resp.data.map(item=>{
         return item.data;
       });
      });
    },
    markRead(id) {
      axios.post("/mark-notif",{id: id}).then((resp) => {
         this.loadData();
      });
    },
    markAllRead() {
      axios.post("/mark-notif").then((resp) => {
        this.loadData();
      });
    }
  },
};
</script>