<!-- daterangepicker -->
<script src="<?php echo assets_url('admin') ?>/plugins/moment/moment.min.js"></script>
<script src="<?php echo assets_url('admin') ?>/plugins/daterangepicker/daterangepicker.js"></script>

<!-- Summernote -->
<script src="<?php echo assets_url('admin') ?>/plugins/summernote/summernote-bs4.min.js"></script>
<!-- overlayScrollbars -->
<script src="<?php echo assets_url('admin') ?>/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>

<!-- SweetAlert2 -->
<script src="<?php echo assets_url('admin') ?>/plugins/sweetalert2/sweetalert2.min.js"></script>
<!-- Toastr -->
<script src="<?php echo assets_url('admin') ?>/plugins/toastr/toastr.min.js"></script>

<!-- DataTables -->
<script src="<?php echo assets_url('admin') ?>/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="<?php echo assets_url('admin') ?>/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="<?php echo assets_url('admin') ?>/plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="<?php echo assets_url('admin') ?>/plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>

<!-- jquery-validation -->
<script src="<?php echo assets_url('admin') ?>/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="<?php echo assets_url('admin') ?>/plugins/jquery-validation/additional-methods.min.js"></script>

<!-- Bootstrap Switch -->
<script src="<?php echo assets_url('admin') ?>/plugins/bootstrap-switch/js/bootstrap-switch.min.js"></script>

<!-- Select2 -->
<script src="<?php echo assets_url('admin') ?>/plugins/select2/js/select2.full.min.js"></script>

<!-- AdminLTE App -->
<script src="<?php echo assets_url('admin') ?>/js/adminlte.min.js"></script>

<!-- AdminLTE for demo purposes -->
<script src="<?php echo assets_url('admin') ?>/js/demo.js"></script>

<script>
  $(function () {
    $("#example1").DataTable({
      "responsive": true,
      "autoWidth": false,
    });

    $("input[data-bootstrap-switch]").each(function(){
      $(this).bootstrapSwitch('state', $(this).prop('checked'));
    });

    $.validator.setDefaults({
      errorElement: 'span',
      errorPlacement: function (error, element) {
        error.addClass('invalid-feedback');
        element.closest('.form-group').append(error);
      },
      highlight: function (element, errorClass, validClass) {
        $(element).addClass('is-invalid');
      },
      unhighlight: function (element, errorClass, validClass) {
        $(element).removeClass('is-invalid');
      }
    });

    (function(){
      var badge = document.getElementById('rm_noti_badge');
      var header = document.getElementById('rm_noti_header');
      var list = document.getElementById('rm_noti_list');
      if (!badge || !header || !list) return;
      var pauseListRefresh = false;
      var refreshBusy = false;
      var intervalId = null;
      var dropdown = list.closest('.nav-item.dropdown');
      if (dropdown && typeof $ !== 'undefined') {
        $(dropdown).on('show.bs.dropdown', function () { pauseListRefresh = true; });
        $(dropdown).on('hidden.bs.dropdown', function () { pauseListRefresh = false; refresh(); });
      }
      list.addEventListener('click', function (e) {
        var a = e.target && e.target.closest ? e.target.closest('a[href]') : null;
        if (a && intervalId) {
          clearInterval(intervalId);
          intervalId = null;
        }
      }, true);

      function esc(s){ return String(s||'').replace(/[&<>"']/g, function(c){ return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]); }); }
      function timeLabel(ts){
        if (!ts) return '';
        var d = new Date(ts.replace(' ', 'T'));
        if (isNaN(d.getTime())) return '';
        return d.toLocaleString();
      }
      function renderItems(items){
        if (!items || !items.length) {
          list.innerHTML = '<span class="dropdown-item text-muted">No notifications</span>';
          return;
        }
        var html = '';
        for (var i=0;i<items.length;i++){
          var it = items[i] || {};
          var fw = (it.is_read ? '' : ' font-weight-bold');
          html += '<div class="dropdown-divider"></div>';
          html += '<a class="dropdown-item'+fw+'" href="'+esc('<?= url('dashboard/notifications/go') ?>')+'/'+String(it.id||0)+'">';
          html += '<div>'+esc(it.title||'')+'</div>';
          if (it.body) html += '<div class="text-muted" style="font-weight:normal;">'+esc(it.body)+'</div>';
          var tl = timeLabel(it.created_at);
          if (tl) html += '<div class="text-muted text-sm">'+esc(tl)+'</div>';
          html += '</a>';
        }
        list.innerHTML = html;
      }

      function refresh(){
        if (refreshBusy || document.visibilityState === 'hidden') {
          return;
        }
        refreshBusy = true;
        var p1 = fetch('<?= url('dashboard/notifications/unread-count') ?>', { credentials: 'same-origin' })
          .then(function(r){ return r.json(); })
          .then(function(resp){
            var c = resp && resp.success ? (resp.count||0) : 0;
            if (c > 0) {
              badge.style.display = '';
              badge.textContent = String(c);
              header.textContent = String(c) + ' Notifications';
            } else {
              badge.style.display = 'none';
              badge.textContent = '0';
              header.textContent = 'Notifications';
            }
          }).catch(function(){});

        var p2 = Promise.resolve();
        if (!pauseListRefresh) {
          p2 = fetch('<?= url('dashboard/notifications/latest') ?>', { credentials: 'same-origin' })
            .then(function(r){ return r.json(); })
            .then(function(resp){ renderItems(resp && resp.success ? (resp.items||[]) : []); })
            .catch(function(){});
        }
        Promise.allSettled([p1, p2]).then(function () { refreshBusy = false; });
      }

      refresh();
      intervalId = setInterval(refresh, 3000);
    })();
  });
</script>
<!-- Page Script -->
<?= $this->renderSection('js') ?>
