<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<style>
.calendar {
  display: grid;
  grid-template-columns: 80px repeat(7, 1fr);
}
.cell {
  padding: 6px;
  text-align: center;
  font-size: 13px;
}
.green { color: #16a34a; }
.red   { color: #dc2626; }
.black { color: #9ca3af; }
</style>

<button class="btn btn-primary"
        data-bs-toggle="modal"
        data-bs-target="#bookingModal"
        data-tutor-id="{{ $tutor->id }}">
  Book Now
</button>

<div class="modal fade" id="bookingModal">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">

      <div class="modal-header">
        <button class="btn btn-sm btn-light" id="prevWeek">←</button>
        <strong id="weekLabel" class="mx-3"></strong>
        <button class="btn btn-sm btn-light" id="nextWeek">→</button>
      </div>

      <div class="modal-body">
        <div id="calendarGrid"></div>
      </div>

    </div>
  </div>
</div>

<script>
let currentWeek = new Date();

function loadCalendar(tutorId) {
  const monday = new Date(currentWeek);
  monday.setDate(monday.getDate() - (monday.getDay() + 6) % 7);

  fetch(`/tutor/${tutorId}/weekly-calendar?week_start=${monday.toISOString().slice(0,10)}`)
    .then(r => r.json())
    .then(renderCalendar);
}

function renderCalendar(data) {
  let html = '<div class="calendar">';
  html += '<div></div>';

  data.days.forEach(d => {
    html += `<div class="cell"><strong>${d.date}</strong></div>`;
  });

  for (let h = 9; h <= 18; h++) {
    html += `<div class="cell">${h}:00</div>`;

    data.days.forEach(day => {
      let weekly = data.weekly[day.day_of_week];
      let color = 'black';

      if (weekly) {
        const slotExists = weekly.slots.some(s => s.start_time === `${h}:00:00`);
        if (slotExists) {
          const key = `${day.date}_${h}:00:00`;
          color = data.bookings[key] ? 'red' : 'green';
        }
      }

      html += `<div class="cell ${color}">${h}:00</div>`;
    });
  }

  html += '</div>';
  document.getElementById('calendarGrid').innerHTML = html;
}

document.getElementById('bookingModal')
  .addEventListener('show.bs.modal', e => {
    loadCalendar(e.relatedTarget.dataset.tutorId);
});

document.getElementById('prevWeek').onclick = () => {
  currentWeek.setDate(currentWeek.getDate() - 7);
  loadCalendar(document.querySelector('[data-tutor-id]').dataset.tutorId);
};
document.getElementById('nextWeek').onclick = () => {
  currentWeek.setDate(currentWeek.getDate() + 7);
  loadCalendar(document.querySelector('[data-tutor-id]').dataset.tutorId);
};
</script>
