<?php $__env->startSection('styles'); ?>
<style>
    .dataTables_wrapper {
            padding-top: 20px;
    }
</style>
<?php $__env->stopSection(); ?>
<?php $__env->startSection('content'); ?>
<?php echo $__env->make('report.attendance.header-menu', ['active_header' => 'total-attendance-report'], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>

<?php if($errors->any()): ?>
    <div class="alert alert-danger m-3">
        <ul class="m-0">
            <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <li><?php echo e($error); ?></li>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </ul>
    </div>
<?php endif; ?>

<div class="card mt-4">
    <div class="card-header py-3  card__head">
        <div class="row">
            <div class="col-md-10">
                <div class="row">
                    <div class="form-group col-lg-3 col-md-3 col-sm-6">
                        <input type="text" id="singleDatePicker" name="date" value="<?php echo e(old('date')); ?>" class="form-control">
                    </div>
                    <div class="form-group col-lg-2 col-md-2 col-sm-6">
                        <button id="search" onclick="viewTable()" class="btn btn-info">Search</button>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="m-0 float-right" id="column-panel-parent">
                    <a class="btn btn-secondary btn__export" href="#"  data-toggle="tooltip" title="Print " onclick="printTable()">
                        <i class="fas fa-print"></i>
                    </a>
                    <a class="btn btn-secondary btn__export" id="pdf-btn" href="#" data-toggle="tooltip" title="Download as PDF">
                        <i class="fas fa-file-pdf"></i>
                    </a>
                    <a class="btn btn-secondary btn__export" href="#" data-toggle="collapse" data-target="#column-toggle-panel">
                        <i class="fas fa-columns"></i>
                    </a>
                    <div id="column-toggle-panel" class="collapse border rounded-bottom shadow">
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="class_name" id="class_name" checked style="display:none;">
                            <label class="column-form-check-label" for="class_name">Class</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="shift_name" id="shift_name" checked style="display:none;">
                            <label class="column-form-check-label" for="shift_name">Shift</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="total_student" id="total_student" checked style="display:none;">
                            <label class="column-form-check-label" for="total_student">Total Student</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="total_present" id="total_present" checked style="display:none;">
                            <label class="column-form-check-label" for="total_present">Total Present</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="total_absent" id="total_absent" checked style="display:none;">
                            <label class="column-form-check-label" for="total_absent">Total Absent</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="total_late" id="total_late" checked style="display:none;">
                            <label class="column-form-check-label" for="total_late">Total Late</label>
                        </div>
                       <button class="restorebutton">Restore Visibility</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card mt-4">
    <div class="row">
        <div class="col-md-12">
            <div class="table-responsive">
                <table class="table" id="attendance-table">
                    <thead class="thead-light">
                        <tr>
                            <th>Class</th>
                            <th>Shift</th>
                            <th>Total Student</th>
                            <th>Total Present</th>
                            <th>Total Absent</th>
                            <th>Total Late</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td colspan="10" class="text-center">No data available in table</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>
<?php $__env->startSection('scripts'); ?>
<script>
$(document).ready(function () {
    // Initialize single date picker
    $('#singleDatePicker').daterangepicker({
        singleDatePicker: true, // Enable single date selection
        showDropdowns: true,    // Optional: Show year and month dropdowns
        // minDate: moment(),      // Optional: Prevent selecting dates before today
        locale: {
            format: 'YYYY-MM-DD', // Format for the selected date
        }
    });

    // Handle the date selection event
    $('#singleDatePicker').on('apply.daterangepicker', function (ev, picker) {
        console.log("Selected Date: " + picker.startDate.format('YYYY-MM-DD'));
    });
});
</script>

<script>
    $('#pdf-btn').on('click', function (e) {
        e.preventDefault(); // Prevent default link behavior
        // Get values from filter fields
        let date = $('#singleDatePicker').val();
        let selectedColumns = [];
        $('.toggle-column:checked').each(function () {
            selectedColumns.push($(this).val());
        });

        $.ajax({
            url: '<?php echo e(route("total-attendance-pdf-export")); ?>', // Route to handle PDF generation
            method: 'POST',
            data: {
                _token: '<?php echo e(csrf_token()); ?>', // Include CSRF token
                'date'   : date,
                'selected_columns': selectedColumns,
            },
            xhrFields: {
                responseType: 'blob', // Important for downloading files
            },
            success: function (data) {
                // Create a URL for the file blob
                const url = window.URL.createObjectURL(new Blob([data]));
                const a = document.createElement('a');
                a.href = url;
                a.download = 'total-attendance-report.pdf'; // Set the file name
                document.body.appendChild(a);
                a.click();
                a.remove();
            },
            error: function (xhr) {
                console.error('Error exporting PDF:', xhr.responseText);
            }
        });
    });

    function restoreDefaultColumns() {
        // Set the default checked states
        $('#class_name').prop('checked', true);
        $('#shift_name').prop('checked', true);
        $('#total_student').prop('checked', true);
        $('#total_present').prop('checked', true);
        $('#total_absent').prop('checked', true);
        $('#total_late').prop('checked', true);
        // Reinitialize the table with the default column selection
        viewTable();
    }

    // Event listener for the "Restore Visibility" button
    $('.restorebutton').on('click', function() {
        restoreDefaultColumns();
    });

    let table; // Store DataTable instance
    // viewTable(); // Initial table load
    function viewTable() {
        // Get filter data
        let date = $('#singleDatePicker').val();

        // Collect selected columns
        let selectedColumns = [];
        $('.toggle-column:checked').each(function () {
            selectedColumns.push($(this).val());
        });

        // Define column configurations and headers
        let columns = [];
        let columnHeaders = [];
        // Define columns dynamically
        columns.push({ data: 'class_name', name: 'class_name', searchable: true });
        columnHeaders.push('Class');

        if (selectedColumns.includes('shift_name')) {
            columns.push({ data: 'shift_name', name: 'shift_name' });
            columnHeaders.push('Shift');
        }
        if (selectedColumns.includes('total_student')) {
            columns.push({ data: 'total_student', name: 'total_student' });
            columnHeaders.push('Total Student');
        }
        if (selectedColumns.includes('total_present')) {
            columns.push({ data: 'total_present', name: 'total_present' });
            columnHeaders.push('Total Present');
        }
        if (selectedColumns.includes('total_absent')) {
            columns.push({ data: 'total_absent', name: 'total_absent' });
            columnHeaders.push('Total Absent');
        }
        if (selectedColumns.includes('total_late')) {
            columns.push({ data: 'total_late', name: 'total_late' });
            columnHeaders.push('Total late');
        }

        // If no columns are selected, handle it
        if (columns.length === 0) {
            if ($.fn.DataTable.isDataTable('#attendance-table')) {
                $('#attendance-table').DataTable().clear().destroy();
            }

            table = $('#attendance-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "<?php echo e(route('total-attendance-report-search')); ?>",
                    type: "POST",
                    data: function (d) {
                        d.selected_columns = selectedColumns;
                        d.date = date;
                    },
                    headers: {
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        handleAjaxError(xhr, textStatus, errorThrown);
                    }
                },
                columns: [],
                language: {
                    processing: "<span class='spinner-border spinner-border-sm' role='status' aria-hidden='true'></span> Loading..."
                },
                paging: true,
                info: true,
                lengthChange: false,
                searching: false,
                ordering: false
            });
        } else {
            if ($.fn.DataTable.isDataTable('#attendance-table')) {
                $('#attendance-table').DataTable().clear().destroy();
            }

            const thead = $('#attendance-table').find('thead');
            thead.empty();
            let headerRow = $('<tr></tr>');
            columnHeaders.forEach(header => {
                headerRow.append(`<th>${header}</th>`);
            });
            thead.append(headerRow);

            table = $('#attendance-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "<?php echo e(route('total-attendance-report-search')); ?>",
                    type: "POST",
                    data: function (d) {
                        d.selected_columns = selectedColumns;
                        d.date = date;
                    },
                    headers: {
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
                    }
                },
                columns: columns,
                language: {
                    processing: "<span class='spinner-border spinner-border-sm' role='status' aria-hidden='true'></span> Loading..."
                },
                responsive: true,
                paging: true,
                info: true,
                lengthChange: true,
                searching: true,
                ordering: true
            });

            // Handle errors globally
            $('#attendance-table').on('xhr.dt', function (e, settings, json, xhr) {
                if (xhr.status >= 400) {
                    handleAjaxError(xhr, xhr.statusText);
                    // Stop DataTables loading spinner
                    table.processing(false);
                }
            });
        }
    }

    // Error handling function
    function handleAjaxError(xhr, textStatus, errorThrown) {
        if (xhr.status === 422) {
            Swal.fire({
              position: "top-end",
              icon: "danger",
              title: "Validation error: Please check your input field.",
              showConfirmButton: false,
              timer:1500
            });
        } else if (xhr.status === 500) {
            alert("Internal Server Error: Please try again later.");
        } else {
            alert(`Unexpected error: ${textStatus}`);
        }
        console.error("Error details:", xhr.responseText);
    }


    $(document).on('change', '.toggle-column', function() {
        // Reinitialize table when column visibility changes
        viewTable();
    });


// print function
function printTable() {
    let reportrange = $('#singleDatePicker').val(); // Get the date value from the input
    const formatDate = (date) => {
        const [year, month, day] = date.split('-'); // Split the date into parts
        return `${month}-${day}-${year}`; // Rearrange into MM-DD-YYYY
    };
    let formattedDate = formatDate(reportrange);

    if (reportrange == null || reportrange === '') {
        Swal.fire({
            icon: 'warning', // Icon type (e.g., 'warning', 'error', 'info', 'success')
            title: 'Selection Required',
            text: 'Please select date before searching.',
            confirmButtonText: 'OK' // Customize the button text
        });
        return; // Prevent the function from proceeding if a required field is missing
    }

    var selectedColumns = [];
    $('.toggle-column:checked').each(function () {
        selectedColumns.push($(this).val());
    });
    // Define the columns and headers dynamically
    let columns = [];
    let columnHeaders = [];

    // Dynamically add other columns based on user selection
    if (selectedColumns.includes('class_name')) {
        columns.push({ data: 'class_name', name: 'class_name' });
        columnHeaders.push('Class');
    }
    if (selectedColumns.includes('shift_name')) {
        columns.push({ data: 'shift_name', name: 'shift_name' });
        columnHeaders.push('Shift');
    }
    if (selectedColumns.includes('total_student')) {
        columns.push({ data: 'total_student', name: 'total_student' });
        columnHeaders.push('Total Student');
    }
    if (selectedColumns.includes('total_present')) {
        columns.push({ data: 'total_present', name: 'total_present' });
        columnHeaders.push('Total Present');
    }
    if (selectedColumns.includes('total_absent')) {
        columns.push({ data: 'total_absent', name: 'total_absent' });
        columnHeaders.push('Total Absent');
    }
    if (selectedColumns.includes('total_late')) {
        columns.push({ data: 'total_late', name: 'total_late' });
        columnHeaders.push('Total late');
    }

    let tableContent = '<table border="1" style="width: 100%; border-collapse: collapse;">';

    tableContent += '<thead><tr>';
    columnHeaders.forEach(function (header) {
        tableContent += '<th style="border: 1px solid #ccc;padding: 5px;text-align: center;">' + header + '</th>';
    });
    tableContent += '</tr></thead><tbody>';

    let hasData = false;
    $('#transport tbody tr').each(function () {
        hasData = true;
        tableContent += '<tr>';
        $(this).find('td').each(function (index) {
            if (columns[index]) {
                tableContent += '<td style="border: 1px solid #ccc;padding: 5px;text-align: center;">' + $(this).text() + '</td>';
            }
        });
        tableContent += '</tr>';
    });

    if (!hasData) {
        tableContent += '<tr><td colspan="7" class="text-center">No data available in table</td></tr>';
    }

    tableContent += '</tbody></table>';

    const logoUrl = "<?php echo e(get_setting_value(Settings::EXPORT_LOGO) ? asset(get_setting_value(Settings::EXPORT_LOGO)) : asset('uploads/images/logo.png') ?? ''); ?>"; 
    const instituteName = "<?php echo e(get_setting_value(Settings::SCHOOL_NAME) ? get_setting_value(Settings::SCHOOL_NAME) : ''); ?>";
    const branch_address = "<?php echo e(get_branch_info()->address ? get_branch_info()->address : ''); ?>";
    const branch_contact_info = "<?php echo e(get_branch_info()->contact_info ? get_branch_info()->contact_info : ''); ?>";
    const currDate = new Date();
    const currentDate =  `${(currDate.getMonth() + 1).toString().padStart(2, '0')}-${currDate.getDate().toString().padStart(2, '0')}-${currDate.getFullYear()}`;

    const primaryInfo = $("#primary-info").html();

    let printWindow = window.open('', '', 'height=800,width=1200');
    printWindow.document.write('<html><head><title>Print</title><style>');
    // Add CSS for alignment
    printWindow.document.write(`<style>
        .header-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 0 20px; /* Add padding to create space between edges and text */
        }
        .header-left {
            text-align: left;
            font-size: 14px;
            font-weight: bold; /* Make hostel name bold */
            flex: 1; /* Ensures it takes available space on the left */
        }
        .header-right {
            text-align: right;
            font-size: 14px;
            font-weight: bold; /* Make date bold */
        }
        table, th, td {
            border: 1px solid #ccc !important; /* Apply border color with high specificity */
            border-collapse: collapse;
        }
        th {
            font-family: sans-serif;
            text-align: center;
            padding: 10px 8px !important;
            background: #eaecf4;
            font-weight: 400 !important;
        }
        td {
            text-align: center;
            padding: 8px;
            color: #292929;
        }
        tr {
            border: 1px solid #ccc; /* Ensure row borders are styled */
        }
        td, th {
            border-color: #ccc; /* Explicitly set border color for td and th */
        }
    </style>`);
    printWindow.document.write('</style></head><body>');
    printWindow.document.write('<div style="text-align: center; margin-bottom: 20px;font-family: sans-serif;color:#1d1d1d ;">');
    printWindow.document.write('<img src="' + logoUrl + '" alt="Institute Logo" style="height: 80px;padding-bottom:10px !important;">');
    printWindow.document.write('<h2 style="margin: 0;">' + instituteName + '</h2>');
    printWindow.document.write('<p style="margin: 0;">' + branch_address + '</p>');
    printWindow.document.write('<p style="margin: 0;">' + branch_contact_info + '</h2>');
    printWindow.document.write('<p style="margin: 0;"><strong>Total Attendance Report</strong></p>');
    printWindow.document.write('</div>');

    //table top info
    printWindow.document.write('<div class="table-top">');
    printWindow.document.write('<table style="border: none !important; width: 100%; margin: 0px 0px 10px 0px; padding: 0px;">');
    printWindow.document.write('<tbody><tr style="width: 100%;border: none !important;">');
    printWindow.document.write('<td style="text-align: left; width: 80%;border: none !important;padding: 0px;"><strong>Filter By: </strong>'+formattedDate+'</td>'); 
    printWindow.document.write('<td style="text-align: right; width: 20%;border: none !important;padding: 0px;"> <strong>Date: </strong>' + currentDate + '</td>'); 
    printWindow.document.write('</tr></tbody></table>');
    printWindow.document.write('</div>');

    printWindow.document.write(tableContent);
    printWindow.document.write('</body></html>');
    printWindow.document.close();

    // Attach the onafterprint event
    printWindow.onafterprint = function () {
        printWindow.close();
    };

    // Add a delay to ensure resources are loaded before printing
    setTimeout(() => {
        printWindow.print();
    }, 500);
}


    // print function
    function printTable2() {
        // Collect selected columns (exclude 'SL' and 'action' columns)
        var selectedColumns = [];
        $('.toggle-column:checked').each(function () {
            selectedColumns.push($(this).val());
        });
        // Define the columns and headers dynamically
        let columns = [];
        let columnHeaders = [];

        // Dynamically add other columns based on user selection
        if (selectedColumns.includes('class_name')) {
            columns.push({ data: 'class_name', name: 'class_name' });
            columnHeaders.push('Class');
        }
        if (selectedColumns.includes('shift_name')) {
            columns.push({ data: 'shift_name', name: 'shift_name' });
            columnHeaders.push('Shift');
        }
        if (selectedColumns.includes('total_student')) {
            columns.push({ data: 'total_student', name: 'total_student' });
            columnHeaders.push('Total Student');
        }
        if (selectedColumns.includes('total_present')) {
            columns.push({ data: 'total_present', name: 'total_present' });
            columnHeaders.push('Total Present');
        }
        if (selectedColumns.includes('total_absent')) {
            columns.push({ data: 'total_absent', name: 'total_absent' });
            columnHeaders.push('Total Absent');
        }
        if (selectedColumns.includes('total_late')) {
            columns.push({ data: 'total_late', name: 'total_late' });
            columnHeaders.push('Total late');
        }
        // Generate the printable table
        let tableContent = '<table border="1" style="width: 100%; border-collapse: collapse;">';
        // Add headers to the printable table
        tableContent += '<thead><tr>';
        columnHeaders.forEach(function (header) {
            tableContent += '<th>' + header + '</th>';
        });
        tableContent += '</tr></thead><tbody>';
        // Check for table data
        let hasData = false;
        $('#attendance-table tbody tr').each(function () {
            hasData = true; // Mark that data is found
            tableContent += '<tr>';
            $(this).find('td').each(function (index) {
                // Ensure only the relevant columns are included based on their index
                if (columns[index]) {
                    tableContent += '<td>' + $(this).text() + '</td>';
                }
            });
            tableContent += '</tr>';
        });
        // If no data, display a "No data available in table" row
        if (!hasData) {
            tableContent += '<tr><td colspan="7" class="text-center">No data available in table</td></tr>';
        }
        tableContent += '</tbody></table>';
        // Open a new window and print the table
        let printWindow = window.open('', '', 'height=800,width=1200');
        printWindow.document.write('<html><head><title>Print</title></head><body>');
        printWindow.document.write('<h1>Total Attendance Report</h1>');
        printWindow.document.write(tableContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.print();
    }

</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /var/www/html/EdueasyCollege/resources/views/report/attendance/total-attendance-report.blade.php ENDPATH**/ ?>