<!-- DataTable JS init -->
<script>
    $(document).ready(function () {
        $("#class-select").change(function () {
            var selectedClass = $(this).val();

            $.ajax({
                url: "fetch_subjects.php", // PHP file to fetch subjects
                method: "POST",
                data: { class: selectedClass },
                success: function (data) {
                    $("#subject-select").html(data);
                }
            });
        });
    });
	
    function Check(frm, ischecked) {
      var checkBoxes = frm.elements['sub_reg_id[]'];

      for (i = 0; i < checkBoxes.length; i++) {
        checkBoxes[i].checked = ischecked; // and just update for all here
      }

    }

    window.onload = function() {
      document.getElementById("selectall").onchange = function() { // <--missing { here
        Check(document.selectform, this.checked); // <----pass the state here
      };
    };
</script>
    <!-- The DataTable initialization script -->
<script>
$(document).ready(function() {
    $('#myTable').DataTable({            
        responsive: true,
        paging: true,        // Enable pagination
        searching: true,     // Enable search box
        pageLength: 50       // Show 50 rows per page
    });
});
</script>



<!-- SweetAlert Trigger -->
<script>
    <?php if (!empty($msg)) { ?>
        Swal.fire({
            position: 'center',
            icon: '<?php echo $alert_type; ?>',
            title: '<?php echo addslashes($msg); ?>',
            showConfirmButton: true,
            confirmButtonText: 'Okay',
        }).then(() => {
            <?php if (!empty($redirect_url)) { ?>
                window.location.href = '<?php echo $redirect_url; ?>';
            <?php } ?>
        });
    <?php } ?>
</script>

<?php
$msg = $_SESSION['msg'] ?? '';
$type = $_SESSION['type'] ?? '';
$redirect_url = $_SESSION['redirect_url'] ?? '';
?>

<!-- SweetAlert Trigger -->
<script>
    <?php if (!empty($msg)) { ?>
        Swal.fire({
            position: 'center',
            icon: '<?php echo $type; ?>',
            title: '<?php echo addslashes($msg); ?>',
            showConfirmButton: true,
            confirmButtonText: 'Okay',
        }).then(() => {
            <?php if (!empty($redirect_url)) { ?>
                window.location.href = '<?php echo $redirect_url; ?>';
            <?php } ?>
        });
    <?php } ?>
</script>
<?php
unset($_SESSION['msg'], $_SESSION['type'], $_SESSION['redirect_url']);
?>
<script>
  $(document).ready(function(){
    $('.datepicker').datepicker({
      format: 'dd/mm/yyyy',
      autoclose: true,
      todayHighlight: true,
      endDate: "0d"
    });
  });
</script>


<script>
function previewImage(event) {
    const input = event.target;
    const preview = document.getElementById('preview');

    if (input.files && input.files[0]) {
        const reader = new FileReader();

        reader.onload = function(e) {
            preview.src = e.target.result;
        }

        reader.readAsDataURL(input.files[0]);
    }
}
</script>

<!-- JavaScript to preview uploaded image -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Preview logic for file inputs
    const fileInputs = document.querySelectorAll('input[type="file"]');
    
    fileInputs.forEach(input => {
        input.addEventListener('change', function (event) {
            const previewId = this.closest('.file-upload-box').dataset.previewId;
            const previewImg = document.getElementById(previewId);

            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    if (previewImg) {
                        previewImg.src = e.target.result;
                        previewImg.style.display = 'inline-block';
                    } else {
                        // If preview <img> doesn't exist, create one dynamically
                        const newImg = document.createElement('img');
                        newImg.id = previewId;
                        newImg.src = e.target.result;
                        newImg.alt = 'Preview';
                        newImg.style.height = (previewId === 'favicon-preview' ? '32px' : '80px');
                        input.closest('.file-upload-box').parentNode.appendChild(newImg);
                    }
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    });
});
</script>

<!-- Print printable area --> 
       <script>
            function printTable() {
                var printContent = document.getElementById('printableArea').innerHTML;
                var originalContent = document.body.innerHTML;
                document.body.innerHTML = printContent;
                window.print();
                document.body.innerHTML = originalContent;
            }
        </script>
<!-- Fetch student subject -->        
<script>
	$(document).ready(function () {
        $("#select-all").click(function () {
            $(".select-student").prop('checked', this.checked);
        });
    });
	
    $(document).ready(function () {
        $("#class-select").change(function () {
            var selectedClass = $(this).val();

            $.ajax({
                url: "fetch_subjects.php", // PHP file to fetch subjects
                method: "POST",
                data: { class: selectedClass },
                success: function (data) {
                    $("#subject-select").html(data);
                }
            });
        });
    });
	
</script>

<!-- Generate Class Broadsheet -->
<script>
    document.getElementById('generateBtn').addEventListener('click', function() {
    var view_upload_class = document.querySelector("select[name='view_upload_class']").value;
    var view_upload_term = document.querySelector("select[name='view_upload_term']").value;
    var view_upload_session = document.querySelector("select[name='view_upload_session']").value;
    
    if (view_upload_class !== "<?php echo $select ?>"
        && view_upload_term !== "<?php echo $select ?>"
        && view_upload_session !== "<?php echo $select ?>") {
        window.location.href = "generate.php?class=" + view_upload_class + "&term=" + view_upload_term + "&session=" + view_upload_session;
    } else {
        alert("Please select valid options for Class, Term, and Session.");
    }
});
</script>

<script>
document.querySelectorAll('.file-upload-box').forEach(box => {
    box.addEventListener('click', function () {
        let input = this.querySelector('input[type="file"]');
        if (input) input.click();
    });
});
</script>
<script>
    $(document).ready(function () {
        $("#class-select").change(function () {
            var selectedClass = $(this).val();

            $.ajax({
                url: "fetch_subjects.php", // PHP file to fetch subjects
                method: "POST",
                data: { class: selectedClass },
                success: function (data) {
                    $("#subject-select").html(data);
                }
            });
        });
    });
</script>

<!-- Attendance datatable -->
<script>
$(document).ready(function() {
    $('#attendanceTable').DataTable({
        paging: false,
        ordering: false,
        info: false,
        responsive: true
    });
});
</script>

<!-- Calculate student total present and absent -->
<script>
document.querySelectorAll('.present, .absent').forEach(input => {
    input.addEventListener('input', () => {
        const row = input.closest('tr');
        const present = parseInt(row.querySelector('.present').value) || 0;
        const absent = parseInt(row.querySelector('.absent').value) || 0;
        row.querySelector('.total').value = present + absent;
    });
});
</script>

