/*
Theme Name: Boliin Child
Theme URI: https://gaviaspreview.com/wp/boliin/
Author URI: https://themeforest.net/user/gavias
Author: Gaviasthemes Team
Description: Child theme for the Boliin theme.
Template: boliin
*/
// === WP Booking Calendar (free): show monthly totals in legend ===
add_action('wp_footer', function(){ ?>
<script>
(function () {
  function countIn(container){
    const table = container.querySelector('table.datepick.wpbc_calendar');
    if(!table) return;

    const cells = table.querySelectorAll('td.datepick-days-cell:not(.datepick-other-month)');
    const counts = {Available:0, Booked:0, Pending:0, Unavailable:0};

    cells.forEach(td=>{
      const c = td.classList;
      if (c.contains('date_approved')) { counts.Booked++; return; }
      if (c.contains('date2approve')) { counts.Pending++; return; }
      if (c.contains('date_available')) { counts.Available++; return; }
      if (c.contains('date_user_unavailable')) { counts.Unavailable++; return; }
    });

    // Find the legend within the same booking form
    const form   = container.closest('.wpbc_container_booking_form') || document;
    const legend = form.querySelector('.block_hints');
    if(!legend) return;

    legend.querySelectorAll('.wpdev_hint_with_text').forEach(block=>{
      const txts = block.querySelectorAll('.block_text');
      if(!txts.length) return;
      const labelEl = txts[txts.length-1];                 // "Available" / "Booked" / ...
      const label   = (labelEl.textContent||'').trim();
      if(!(label in counts)) return;

      const old = labelEl.querySelector('.af-count');      // remove previous
      if (old) old.remove();
      const s = document.createElement('span');
      s.className = 'af-count';
      s.style.marginLeft = '6px';
      s.textContent = '— ' + counts[label];
      labelEl.appendChild(s);
    });
  }

  function recalcAll(){
    document.querySelectorAll('div[id^="calendar_booking"]').forEach(countIn);
  }

  // Recalculate on initial load and whenever the calendar DOM changes (month nav)
  const mo = new MutationObserver(muts=>{
    if (muts.some(m =>
      Array.from(m.addedNodes||[]).some(n =>
        n.nodeType===1 && (n.matches?.('table.datepick.wpbc_calendar,.datepick-one-month,.datepick-days-row') ||
                           n.querySelector?.('table.datepick.wpbc_calendar'))
      )
    )) recalcAll();
  });
  mo.observe(document.body, {childList:true, subtree:true});

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', recalcAll);
  } else {
    recalcAll();
  }
})();
</script>
<?php });
