<?php $__env->startSection('title', 'Bel Otomatis'); ?>

<?php $__env->startSection('content'); ?>
<div class="container mt-4">
  <div class="form-check form-switch mb-4 left">
    <input class="form-check-input" type="checkbox" id="modeToggle">
    <label class="form-check-label" for="modeToggle"><b>Mode Ujian</b></label>
  </div>

  
  <ul class="nav nav-tabs d-none" id="modeTab" role="tablist">
    <li class="nav-item">
      <a class="nav-link active" id="reguler-tab" data-bs-toggle="tab" href="#reguler" role="tab"
        aria-controls="reguler" aria-selected="true">Reguler</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="ujian-tab" data-bs-toggle="tab" href="#ujian" role="tab" aria-controls="ujian"
        aria-selected="false">Ujian</a>
    </li>
  </ul>

  <!-- Tab Content -->
  <div class="tab-content" id="modeTabContent">
    <div class="tab-pane fade show active" id="reguler" role="tabpanel" aria-labelledby="reguler-tab">
      <?php echo $__env->make('jadwal_bel.reguler', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    </div>
    <div class="tab-pane fade" id="ujian" role="tabpanel" aria-labelledby="ujian-tab">
      <?php echo $__env->make('jadwal_bel.ujian', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
    </div>
  </div>
  


  <!-- Modal saat halaman dibuka -->
  <div class="modal fade" id="welcomeModal" tabindex="-1" aria-labelledby="welcomeModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content text-center">
        <div class="modal-body">
          <div class="modal-header bg-primary text-white">
            <h5 class="modal-title" id="welcomeModalLabel">Aplikasi Bel Sekolah Otomatis</h5>
          </div>
          
          <iframe src="https://gitek.id/" frameborder="0" width="460px" height="350px"></iframe>
          <button id="aktifkanBel" class="btn btn-lg btn-success shadow px-2 py-1"> Aktifkan Bel Otomatis</button>
        </div>
      </div>
    </div>
  </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>


<script>
  document.addEventListener('DOMContentLoaded', function () {
    const toggle = document.getElementById('modeToggle');
    const audioPlayer = document.getElementById('belAudio');
    const statusElReguler = document.querySelector('#reguler #jam-sekarang');
    const hariElReguler = document.querySelector('#reguler #hari-ini');
    const statusElUjian = document.querySelector('#ujian #jam-sekarang');
    const hariElUjian = document.querySelector('#ujian #hari-ini');
    const jadwalReguler = <?php echo json_encode($jadwals_reguler, 15, 512) ?>;
    const jadwalUjian = <?php echo json_encode($jadwals_ujian, 15, 512) ?>;

    let mode = 'reguler';
    let lastPlayedTime = null;
    let audioDiizinkan = false;

    function getJadwalHariIni() {
      return mode === 'reguler' ? jadwalReguler : jadwalUjian;
    }

    function getStatusEl() {
      return mode === 'reguler' ? statusElReguler : statusElUjian;
    }

    function getHariEl() {
      return mode === 'reguler' ? hariElReguler : hariElUjian;
    }

    toggle.addEventListener('change', function () {
      if (toggle.checked) {
        mode = 'ujian';
        document.querySelector('#ujian-tab').click();
      } else {
        mode = 'reguler';
        document.querySelector('#reguler-tab').click();
      }
    });

    $('#welcomeModal').modal('show');

    document.getElementById('aktifkanBel').addEventListener('click', () => {
      $('#welcomeModal').modal('hide');
      audioPlayer.src = "<?php echo e(asset('storage/aktif.mp3')); ?>";
      audioPlayer.play().then(() => {
        audioDiizinkan = true;
        alert("Bel otomatis diaktifkan.");
      }).catch((err) => {
        console.warn("Gagal mengaktifkan audio:", err);
      });
    });

    function updateJam() {
      const now = new Date();
      const jamStr = now.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
      const hariStr = now.toLocaleDateString('id-ID', { weekday: 'long' });

      getStatusEl().innerText = jamStr;
      getHariEl().innerText = hariStr;

      const jamSekarang = now.toTimeString().slice(0, 5); // HH:MM

      getJadwalHariIni().forEach(jadwal => {
      const hariJadwal = jadwal.hari.split(',').map(h => h.trim());
        if (
          hariJadwal.includes(hariStr) &&
          jadwal.jam.slice(0, 5) === jamSekarang &&
          lastPlayedTime !== jamSekarang
        ) {
          const filePath = `<?php echo e(asset('storage')); ?>/${jadwal.file_suara}`;

          if (!audioDiizinkan) {
            console.warn("Audio belum diizinkan user.");
            return;
          }

          if (!audioPlayer.paused && !audioPlayer.ended) {
            console.log("Audio sedang diputar, skip.");
            return;
          }

          lastPlayedTime = jamSekarang;
          let playCount = 0;

          const playAudio = () => {
            audioPlayer.src = filePath;
            audioPlayer.load();
            audioPlayer.play()
              .then(() => {
                playCount++;
                console.log(`Memutar ke-${playCount}:`, filePath);
                if (playCount === 1) {
                  showModal(jadwal.keterangan, jadwal.jam);
                }
              })
              .catch(e => console.warn('Gagal putar:', e));
          };

          audioPlayer.onended = () => {
            if (playCount < 2) {
              playAudio();
            } else {
              audioPlayer.onended = null;
            }
          };

          playAudio();
        }
      });
    }

    function showModal(keterangan, jam) {
      document.getElementById('modalKeterangan').innerText = keterangan;
      document.getElementById('modalJam').innerText = `Pukul ${jam}`;
      $('#belModal').modal('show');
    }

    setInterval(updateJam, 1000);
    updateJam();
  });
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/bel-sekolah/resources/views/jadwal_bel/otomatis.blade.php ENDPATH**/ ?>