<style>
    /* Hide default checkbox */
    input[type="checkbox"] {
        appearance: none;
        width: 20px;
        height: 20px;
        border: 2px solid #4CAF50; /* Green border for available */
        border-radius: 5px;
        cursor: pointer;
        position: relative;
    }

    /* Available slot checkbox (Green) */
    input[type="checkbox"]:checked {
        background-color: #4CAF50; /* Green when selected */
    }

    /* Booked slot checkbox (Red, Disabled) */
    input[type="checkbox"].booked {
        background-color: #ff4d4d !important; /* Red */
        border-color: #ff4d4d !important;
        cursor: not-allowed;
    }

    /* Disable hover effect for booked slots */
    input[type="checkbox"].booked:hover {
        opacity: 1;
    }
    

</style>

<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Edit Diagnostic Booking Slots</h4>
              
  <div class="row"><div class="col-md-6">
      <div class="card mb-4">
          <form method="post" action="#" id="inputform" enctype="multipart/form-data">
        <div class="card-body">
            
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Date *</label>
            <input
              type="date"
              class="form-control"
              id="dateInput"
              placeholder="Date" 
              name="date" 
              required 
              value="<?=$diagnostic_bookings[0]['date']?>"
            />

          </div>
         
         <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Time Slots *</label>
         
         
         <div id="slotsContainer">
            <?php foreach (['morning', 'afternoon', 'evening'] as $section): ?>
                <?php if (!empty($slots[$section])): ?>
                    <div class="mb-3">
                        <strong><?= ucfirst($section) ?></strong><br>
                        <?php foreach ($slots[$section] as $slot): 
                            $is_booked = isset($slot['booking_status']) && $slot['booking_status'] === "booked";
                            $is_checked = isset($slot_status[$slot['time']]);
                            ?>
                            <label class="<?= $is_booked ? 'booked' : '' ?>">
                                <input type="checkbox"
                                    class="time-slot <?= $is_booked ? 'booked' : '' ?>"
                                    name="time[]"
                                    value="<?= $slot['id'] ?>"
                                    <?= $is_checked ? 'checked' : '' ?>
                                    <?= $is_booked ? 'disabled' : '' ?>>
                                <span><?= $slot['time'] ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>

        
       
            <!-- All your current PHP-rendered slot blocks go here -->
        </div>
        

        <div class="mb-3">
            <strong>Legend:</strong><br>
            <label>
                <input type="checkbox" disabled style="background-color: #ff4d4d; border-color: #ff4d4d;"> 
                <span>Booked (Cannot Uncheck)</span>
            </label><br>
        
            <!--<label>-->
            <!--    <input type="checkbox" checked disabled style="background-color: #4CAF50; border-color: #4CAF50;"> -->
            <!--    <span>Previously Selected (Can Uncheck)</span>-->
            <!--</label><br>-->
        
            <label>
                <input type="checkbox" disabled style="border: 2px solid #4CAF50;"> 
                <span>Available (Can Select)</span>
            </label>
        </div>
        
        </div>
      </div>
       <!--<button type="button" name="sub" value="sub" class="btn btn-success" id="saveBtn">Submit</button>-->
      </form>
      <a href="<?=base_url('admin/register/ongoing_diagnostic_bookings')?>"><button type="button" class="btn btn-danger">Cancel</button></a>
    </div></div>
</div>

<script>
    // Set today's date as the minimum selectable date
    document.addEventListener("DOMContentLoaded", function () {
        let today = new Date().toISOString().split('T')[0]; // Format YYYY-MM-DD
        document.getElementById("dateInput").setAttribute("min", today);
    });
</script>

<script>
  $('#dateInput').on('change', function() {
    const selectedDate = $(this).val();
    const id = '<?= $diagnostic_bookings[0]['id'] ?>';

    $.post('<?= base_url("admin/register/get_diagnostic_bookingg_slots_by_date") ?>', {
        selected_date: selectedDate,
        id: id
    }, function(res) {
        let data = JSON.parse(res);
        if (data.status) {
            renderSlots(data.slots);
        } else {
            $('#slotsContainer').html('<div class="text-danger">No slots available for this date.</div>');
        }
    });
  });

  function renderSlots(slots) {
    let html = '';
    const sections = ['morning', 'afternoon', 'evening'];

    sections.forEach(section => {
        if (slots[section]?.length > 0) {
            html += `<div class="mb-3">
                        <strong>${capitalize(section)}</strong><br>`;
            slots[section].forEach(slot => {
                const isBooked = slot.booking_status === 'booked';
                const isChecked = slot.checked == true;
                const checked = isChecked ? 'checked' : '';
                const disabled = isBooked ? 'disabled' : '';
                const labelClass = isBooked ? 'booked' : '';

                html += `<label class="${labelClass}">
                            <input type="checkbox" name="time[]" class="time-slot ${labelClass}" value="${slot.id}" ${checked} ${disabled}>
                            <span>${slot.time}</span>
                         </label> `;
            });
            html += `</div>`;
        }
    });

    $('#slotsContainer').html(html);
  }

  function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  // Save slot selection
  $(document).on("change", ".time-slot", function () {
      if ($(this).is(':disabled')) return;

      $(".time-slot").not(this).prop('checked', false); // Allow only one selection

      const id = "<?= $diagnostic_bookings[0]['id'] ?>";
      const date = $('#dateInput').val();
      const time = $(this).val();
      const isChecked = $(this).is(':checked') ? 1 : 0;

      $.ajax({
          url: "<?= base_url('admin/register/edit_diagnostic_booking_slot_data') ?>",
          type: "POST",
          data: {
              date: date,
              time: time,
              status: isChecked,
              id: id
          },
          success: function (response) {
              const res = JSON.parse(response);
              if (res.success) {
                  showToast('Success', res.message, 'success');
              } else {
                  showToast('Error', res.message, 'error');
              }
          }
      });
  });
</script>

<!-- Toastr CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
<!-- Toastr JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>


<script>
// Show toast using jQuery
function showToast(title, message, type) {
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-right",
        timeOut: "3000",
    };

    if (type === 'success') {
        toastr.success(message, title);
    } else if (type === 'error') {
        toastr.error(message, title);
    } else if (type === 'info') {
        toastr.info(message, title);
    } else if (type === 'warning') {
        toastr.warning(message, title);
    }
}


</script>
            