@extends('layouts.master')
@section('styles')
<style>
    .dataTables_wrapper {
            padding-top: 20px;
    }
</style>
@endsection
@section('content')
@include('report.attendance.header-menu', ['active_header' => 'type-wise-attendance-report'])

@if($errors->any())
    <div class="alert alert-danger m-3">
        <ul class="m-0">
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@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="reportrange" name="date" class="form-control">
                    </div>
                    <div class="form-group col-lg-2 col-md-2 col-sm-6">
                        {{ generateDropdown(Status::ATTENDANCE_STATUS, 'class="form-control text-capitalize" id="attendance_type" name="attendance_type" required', old('attendance_type'), "--Type--") }}
                    </div>

                    <div class="form-group col-lg-2 col-md-2 col-sm-6">
                        {{ generateDropdown($studentClasses, 'class="form-control student_class" id="student_class_id" name="student_class_id" required', $student_class_id, "Class") }}
                    </div>
                    <div class="form-group col-lg-2 col-md-2 col-sm-6">
                        {{ generateDropdown($shifts, 'class="form-control shift_id" id="shift_id" name="shift_id" required', $shift_id, "Shift") }}
                    </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="excel-btn" href="#" data-toggle="tooltip" title="Download as excel">
                        <i class="fas fa-file-excel"></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="student_id" id="student_id" checked style="display:none;">
                            <label class="column-form-check-label" for="student_id">Student ID</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="roll" id="roll" checked style="display:none;">
                            <label class="column-form-check-label" for="roll">Roll</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="student_name" id="student_name" checked style="display:none;">
                            <label class="column-form-check-label" for="student_name">Name</label>
                        </div>

                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="mobile_number" id="mobile_number" checked style="display:none;">
                            <label class="column-form-check-label" for="mobile_number">Mobile Number</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="total_count" id="total_count" checked style="display:none;">
                            <label class="column-form-check-label" for="total_count">Count</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>Std. ID</th>
                            <th>Roll</th>
                            <th>Name</th>
                            <th>Mobile Number</th>
                            <th>Count</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td colspan="10" class="text-center">No data available in table</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
@stop
@section('scripts')
<script>
    $('#pdf-btn').on('click', function (e) {
        e.preventDefault(); // Prevent default link behavior
        // Get filter data
        let date = $('#reportrange').val();
        let attendance_type = $('#attendance_type').val();
        let student_class_id = $('#student_class_id').val();
        let shift_id = $('#shift_id').val();

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

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

        $.ajax({
            url: '{{ route("type-wise-attendance-pdf-export") }}', // Route to handle PDF generation
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}', // Include CSRF token
                'date'   : date,
                'attendance_type'   : attendance_type,
                'student_class_id'   : student_class_id,
                'shift_id'   : shift_id,
                '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 = 'date-to-date-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);
            }
        });
    });

    $('#excel-btn').on('click', function(e){
        e.preventDefault(); // Prevent default link behavior
        // Get filter data
        let date = $('#reportrange').val();
        let attendance_type = $('#attendance_type').val();
        let student_class_id = $('#student_class_id').val();
        let shift_id = $('#shift_id').val();

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

        let selectedColumns = [];
        $('.toggle-column:checked').each(function () {
            selectedColumns.push($(this).val());
        });
        $.ajax({
            url: '{{ route("type-wise-attendance-excel-export") }}',
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}', // Include CSRF token
                'date'   : date,
                'attendance_type'   : attendance_type,
                'student_class_id'   : student_class_id,
                'shift_id'   : shift_id,
                '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 = 'type-wise-attendance.xlsx'; // Set the file name
                document.body.appendChild(a);
                a.click();
                a.remove();
            },
            error: function (xhr) {
                console.error('Error exporting Excel:', xhr.responseText);
            }
        });
    });



    function restoreDefaultColumns() {
        // Set the default checked states
        $('#student_id').prop('checked', true);
        $('#roll').prop('checked', true);
        $('#student_name').prop('checked', true);
        $('#mobile_number').prop('checked', true);
        $('#total_count').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 = $('#reportrange').val();
        let attendance_type = $('#attendance_type').val();
        let student_class_id = $('#student_class_id').val();
        let shift_id = $('#shift_id').val();

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


        // 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: 'student_id', name: 'student_id', searchable: true });
        columnHeaders.push('Student ID');

        if (selectedColumns.includes('roll')) {
            columns.push({ data: 'roll', name: 'roll' });
            columnHeaders.push('Roll');
        }
        if (selectedColumns.includes('student_name')) {
            columns.push({ data: 'student_name', name: 'student_name' });
            columnHeaders.push('Name');
        }
        if (selectedColumns.includes('mobile_number')) {
            columns.push({ data: 'mobile_number', name: 'mobile_number' });
            columnHeaders.push('Mobile Number');
        }
        if (selectedColumns.includes('total_count')) {
            columns.push({ data: 'total_count', name: 'total_count' });
            columnHeaders.push('Count');
        }

        // 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: "{{ route('type-wise-attendance-report-search') }}",
                    type: "POST",
                    data: function (d) {
                        d.selected_columns = selectedColumns;
                        d.date = date;
                        d.attendance_type = attendance_type;
                        d.student_class_id = student_class_id;
                        d.shift_id = shift_id;
                    },
                    headers: {
                        'X-CSRF-TOKEN': '{{ 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: "{{ route('type-wise-attendance-report-search') }}",
                    type: "POST",
                    data: function (d) {
                        d.selected_columns = selectedColumns;
                        d.date = date;
                        d.attendance_type = attendance_type;
                        d.student_class_id = student_class_id;
                        d.shift_id = shift_id;
                    },
                    headers: {
                        'X-CSRF-TOKEN': '{{ 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);
                }
            });
        }
    }




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


// print function
function printTable() {

    let reportrange = $('#reportrange').val();
    // Split the date range into start and end dates
    const [startDate, endDate] = reportrange.split(' - ');
    // Function to reformat a date from DD/MM/YYYY to YYYY-MM-DD
    const reformatDate = (date) => {
        const [day, month, year] = date.split('/');
        return `${day}-${month}-${year}`;
    };
    // Reformat the dates
    const formattedStartDate = reformatDate(startDate);
    const formattedEndDate = reformatDate(endDate);

    let selected_class = $('#student_class_id option:selected').text();
    let selected_shift = $('#shift_id option:selected').text();
    let student_class_id = $('#student_class_id').val();
    let shift_id = $('#shift_id').val();
    let attendance_type = $('#attendance_type').val();
    // Check if either student_class_id or shift_id is null
    if (student_class_id == null || student_class_id === '' || shift_id == null || shift_id === '' || attendance_type == null || attendance_type === '') {
        Swal.fire({
            icon: 'warning', // Icon type (e.g., 'warning', 'error', 'info', 'success')
            title: 'Selection Required',
            text: 'Please select Type, Class, Shift 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('student_id')) {
        columns.push({ data: 'student_id', name: 'student_id' });
        columnHeaders.push('Student ID');
    }
    if (selectedColumns.includes('roll')) {
        columns.push({ data: 'roll', name: 'roll' });
        columnHeaders.push('Roll');
    }
    if (selectedColumns.includes('student_name')) {
        columns.push({ data: 'student_name', name: 'student_name' });
        columnHeaders.push('Name');
    }
    if (selectedColumns.includes('mobile_number')) {
        columns.push({ data: 'mobile_number', name: 'mobile_number' });
        columnHeaders.push('Mobile Number');
    }
    if (selectedColumns.includes('total_count')) {
        columns.push({ data: 'total_count', name: 'total_count' });
        columnHeaders.push('Count');
    }

    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 = "{{ get_setting_value(Settings::EXPORT_LOGO) ? asset(get_setting_value(Settings::EXPORT_LOGO)) : asset('uploads/images/logo.png') ?? '' }}";
    const instituteName = "{{ get_setting_value(Settings::SCHOOL_NAME) ? get_setting_value(Settings::SCHOOL_NAME) : '' }}";
    const branch_address = "{{ get_branch_info()->address ? get_branch_info()->address : '' }}";
    const branch_contact_info = "{{ get_branch_info()->contact_info ? get_branch_info()->contact_info : '' }}";
    const currentDate1 = new Date();
    const currentDate = currentDate1.toLocaleDateString('en-GB').replace(/\//g, '-');
    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>Attendance Type Wise 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>Class: </strong>'+selected_class+'<strong> Shift: </strong>'+selected_shift+'<strong> Type: </strong>'+attendance_type+'<strong> Date: </strong>' + formattedStartDate +' <strong>To</strong> ' +formattedEndDate+ '</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 printTable22() {
        // 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('student_id')) {
            columns.push({ data: 'student_id', name: 'student_id' });
            columnHeaders.push('Student ID');
        }
        if (selectedColumns.includes('roll')) {
            columns.push({ data: 'roll', name: 'roll' });
            columnHeaders.push('Roll');
        }
        if (selectedColumns.includes('student_name')) {
            columns.push({ data: 'student_name', name: 'student_name' });
            columnHeaders.push('Name');
        }
        if (selectedColumns.includes('mobile_number')) {
            columns.push({ data: 'mobile_number', name: 'mobile_number' });
            columnHeaders.push('Mobile Number');
        }
        if (selectedColumns.includes('total_count')) {
            columns.push({ data: 'total_count', name: 'total_count' });
            columnHeaders.push('Count');
        }
        // 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><strong>Attendance Report:</strong>Type Wise Attendance Report</h1>');
        printWindow.document.write(tableContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.print();
    }

</script>
@endsection
