<?php 
/*echo '<pre>';
print_r($slots);
echo '</pre>';exit;*/
?>

<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Add Diagnostic 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="dateInput" class="form-label">Date *</label>
              <input
                type="date"
                class="form-control"
                id="dateInput"
                name="date"
                placeholder="Date"
                required />
            </div>

         
          
          <!--<div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Time Slots *</label>
                <div class="mb-3">
                    <strong>Morning</strong><br>
                    <?php foreach($slots['morning'] as $morning){?>
                    <input type="checkbox" name="time[]" value="<?=$morning['time']?>"> <?=$morning['time']?>
                    <?php } ?>
                </div>
                
                <div class="mb-3">
                    <strong>Afternoon</strong><br>
                    <?php foreach($slots['afternoon'] as $afternoon){?>
                    <input type="checkbox" name="time[]" value="<?=$afternoon['time']?>"> <?=$afternoon['time']?>
                    <?php } ?>
                </div>
                
               <div class="mb-3">
                    <strong>Evening</strong><br>
                    <?php foreach($slots['evening'] as $evening){?>
                    <input type="checkbox" name="time[]" value="<?=$evening['time']?>"> <?=$evening['time']?>
                    <?php } ?>
                </div>
          </div>-->
          
            <div class="mb-3">
                <label for="exampleFormControlInput1" class="form-label">Time Slots *</label>
                <div id="slotContainer">
                    <p class="text-muted">Please select a date to view available slots.</p>
                </div>
            </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/diagnostic_slots')?>"><button type="button" class="btn btn-danger">Cancel</button></a>
    </div></div>
</div>

<script>
    document.getElementById('dateInput').addEventListener('keydown', function(e) {
        e.preventDefault(); // Prevent manual typing
    });

</script>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const dateInput = document.getElementById('dateInput');
        const slotContainer = document.getElementById('slotContainer');
    
        const today = new Date().toISOString().split('T')[0];
        dateInput.setAttribute('min', today);
        dateInput.value = ''; // Ensure no date is selected initially
    
        // Remove the auto-trigger for slot loading
        // So user must select date manually
    });

</script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const dateInput = document.getElementById('dateInput');
    const slotContainer = document.getElementById('slotContainer');

    // Set today's date as minimum
    const today = new Date().toISOString().split('T')[0];
    dateInput.setAttribute('min', today);

    dateInput.addEventListener('change', function () {
        const selectedDate = this.value;

        if (!selectedDate) return;

        fetch("<?= base_url('admin/register/get_diagnostic_slots_by_date') ?>", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: "date=" + encodeURIComponent(selectedDate)
        })
        .then(response => response.json())
        .then(slots => {
            let html = '';
            const sections = ['morning', 'afternoon', 'evening'];

            let hasSlots = false;

            sections.forEach(section => {
                if (slots[section] && slots[section].length > 0) {
                    hasSlots = true;
                    html += `<div class="mb-2"><strong>${section.charAt(0).toUpperCase() + section.slice(1)}</strong><br>`;
                    slots[section].forEach((slot, i) => {
                        const id = `${section}_${i}`;
                        html += `
                            <label for="${id}" class="me-2">
                                <input type="checkbox" name="time[]" id="${id}" value="${slot.time}"> ${slot.time}
                            </label>`;
                    });
                    html += `</div>`;
                }
            });

            if (!hasSlots) {
                html = '<p class="text-danger">No available slots for the selected date.</p>';
            }

            slotContainer.innerHTML = html;
        })
        .catch(err => {
            slotContainer.innerHTML = '<p class="text-danger">Failed to load slots. Please try again.</p>';
            console.error(err);
        });
    });
});
</script>


<script>
$(document).ready(function () {
    $('#saveBtn').on('click', function () {
        let isValid = true;

        // Validate required fields
        $('#inputform [required]').each(function () {
            let value = $(this).val(); // Get the value
            if (Array.isArray(value)) {
                value = value.join(''); // Convert array to string
            }
            value = value ? value.toString().trim() : ''; // Convert value to string and trim

            if (value === '') {
                isValid = false;
                $(this).addClass('is-invalid'); // Add error styling
                showToast('Error', `${$(this).attr('placeholder')} is required`, 'error');
            } else {
                $(this).removeClass('is-invalid'); // Remove error styling
                $(this).addClass('is-valid'); // Mark as valid
            }
        });
        

        if (isValid) {
            // If all fields are valid, submit the form
            const form = $('#inputform')[0];
            const formData = new FormData(form);

            $.ajax({
                url: '<?= base_url("admin/register/insert_diagnostic_slots"); ?>', // Your endpoint
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    const res = JSON.parse(response);
                    if (res.success) {
                        showToast('Success', res.message, 'success');
                        $('#inputform')[0].reset(); // Reset the form
                        $('.form-control').removeClass('is-valid'); // Clear valid states
                        window.location.href = '<?= base_url("admin/register/diagnostic_slots") ?>';
                    } else {
                        showToast('Error', res.message, 'error');
                    }
                },
                error: function () {
                    showToast('Error', 'An unexpected error occurred.', 'error');
                },
            });
        } else {
            // Scroll to the first invalid field
            $('html, body').animate({
                scrollTop: $('.is-invalid:first').offset().top - 100,
            }, 500);
        }
    });

    // Remove validation feedback on input
    $('#inputform .form-control').on('input change', function () {
        if ($(this).val().trim() !== '') {
            $(this).removeClass('is-invalid').addClass('is-valid');
        } else {
            $(this).removeClass('is-valid').addClass('is-invalid');
        }
    });
});

</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>
            