@extends('layouts.master')
@section('content')
@include('report.hostel.header-menu', ['active_header' => 'hostel-wise-report'])
<div class="card mt-4">
    <div class="card-header py-3  card__head">
        <div class="row">
            <div class="col-md-9">
                <div class="row">
                    <div class="form-group col-lg-3 col-md-3 col-sm-6">
                        {{ generateDropdown($hostels, 'class="form-control hostel_id" id="hostel_id" name="hostel_id" required',  $hostel_id ?? old('hostel_id'), "Select Hostel") }}
                    </div>
                    <div class="form-group col-lg-3 col-md-3 col-sm-6">
                        <button id="search" onclick="viewTable()" class="btn btn-info">Search</button>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <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" title="Toggle column">
                        <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_name" id="student_name" checked style="display:none;">
                            <label class="column-form-check-label" for="student_name">Student Name</label>
                        </div>
                        <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="hostel_room_id" id="hostel_room_id" checked style="display:none;">
                            <label class="column-form-check-label" for="hostel_room_id">Room No</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="guardian_contact" id="guardian_contact" checked style="display:none;">
                            <label class="column-form-check-label" for="guardian_contact">Guardian Contact</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="room_type_id" id="room_type_id" checked style="display:none;">
                            <label class="column-form-check-label" for="room_type_id">Room Type</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="cost" id="cost" checked style="display:none;">
                            <label class="column-form-check-label" for="cost">Cost Per Bed</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 pt-3" id="hostel_table">
                    <thead class="thead-light">
                        <tr>
                            <th>Name</th>
                            <th>Std. ID</th>
                            <th>Guardian Contact</th>
                            <th>Room No</th>
                            <th>Room Type</th>
                            <th>Cost Per Bed</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td colspan="6" 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 values from filter fields
        let hostel_id = $('#hostel_id').val();
        if (!hostel_id) {
            Swal.fire({
                icon: 'warning', // You can change the icon (e.g., 'error', 'info', 'success')
                title: 'Hostel Not Selected',
                text: 'Please select a hostel before searching.',
                confirmButtonText: 'OK' // Customize the button text
            });
            return;  // Prevent the function from proceeding if no hostel is selected
        }

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

        $.ajax({
            url: '{{ route("hostel-wise-pdf-report") }}', // Route to handle PDF generation
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}', // Include CSRF token
                'hostel_id': hostel_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 = 'hostel-wise-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 value from filter fields
        let hostel_id = $('#hostel_id').val();
        if (!hostel_id) {
            Swal.fire({
                icon: 'warning', // You can change the icon (e.g., 'error', 'info', 'success')
                title: 'Hostel Not Selected',
                text: 'Please select a hostel before searching.',
                confirmButtonText: 'OK' // Customize the button text
            });
            return;  // Prevent the function from proceeding if no hostel is selected
        }

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

        $.ajax({
            url: '{{ route("hostel-wise-excel-report") }}',
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}', // Include CSRF token
                'hostel_id': hostel_id,
                'selected_columns': selectedColumns,
            },
            xhrFields: {
                responseType: 'blob', // Important for downloading files
            },
            success: function (data) {
                console.log(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 = 'hostel-wise-report.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_name').prop('checked', true);
        $('#student_id').prop('checked', true);
        $('#hostel_room_id').prop('checked', true);
        $('#guardian_contact').prop('checked', true);
        $('#room_type_id').prop('checked', true);
        $('#cost').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 hostelName = ''; // Declare globally to store hostel name
    // Capture the hostel name when the user selects a hostel
    document.getElementById("hostel_id").addEventListener("change", function() {
      let selectedOption = this.options[this.selectedIndex];  // Get the selected option
      hostelName = selectedOption.text;  // Get the name (text) of the selected option
    });



    let table; // Store DataTable instance
    function viewTable(){
        // Get filter data
        let hostel_id = $('#hostel_id').val();
        // Check if hostel_id is not selected

        if (!hostel_id) {
            Swal.fire({
                icon: 'warning', // You can change the icon (e.g., 'error', 'info', 'success')
                title: 'Hostel Not Selected',
                text: 'Please select a hostel before searching.',
                confirmButtonText: 'OK' // Customize the button text
            });
            return;  // Prevent the function from proceeding if no hostel is selected
        }

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

        if(selectedColumns.includes('student_id')) {
            columns.push({ data: 'student_id', name: 'student_id',  });
            columnHeaders.push('Student ID');
        }
        if(selectedColumns.includes('hostel_room_id')) {
            columns.push({ data: 'hostel_room_id', name: 'hostel_room_id',  });
            columnHeaders.push('Room No');
        }
        if(selectedColumns.includes('guardian_contact')) {
            columns.push({ data: 'guardian_contact', name: 'guardian_contact',  });
            columnHeaders.push('Guardian Contact');
        }
        if(selectedColumns.includes('room_type_id')) {
            columns.push({ data: 'room_type_id', name: 'room_type_id',  });
            columnHeaders.push('Room Type');
        }
        if(selectedColumns.includes('cost')) {
            columns.push({ data: 'cost', name: 'cost',  });
            columnHeaders.push('Cost Per Bed');
        }

        // If no columns are selected, show a custom message
        if(columns.length === 0) {
            // Destroy any previous DataTable instance if it exists
            if($.fn.DataTable.isDataTable('#hostel_table')) {
                $('#hostel_table').DataTable().clear().destroy();
            }

            // Initialize DataTable with no columns
            table = $('#hostel_table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('hostel-wise-report-search') }}",
                    type: "POST",
                    data: function(d) {
                        d.selected_columns = selectedColumns; // Pass empty selected columns
                    },
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    }
                },
                columns: [], // No columns when none selected
                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{
            // Destroy previous DataTable if it exists
            if ($.fn.DataTable.isDataTable('#hostel_table')) {
                $('#hostel_table').DataTable().clear().destroy();
            }
            // Rebuild table headers
            const thead = $('#hostel_table').find('thead');
            thead.empty();
            let headerRow = $('<tr></tr>');
            columnHeaders.forEach(header => {
                headerRow.append(`<th>${header}</th>`);
            });
            thead.append(headerRow);

            // Destroy existing DataTable instance if it exists
            if ($.fn.DataTable.isDataTable('#hostel_table')) {
                $('#hostel_table').DataTable().clear().destroy();
            }

            // Initialize DataTable
            table = $('#hostel_table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('hostel-wise-report-search') }}",
                    type: "POST",
                    data: function (d) {
                        d.selected_columns = selectedColumns;
                        d.hostel_id = hostel_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
            });
        }
    }

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


function printTable() {
    let hostel_id = $('#hostel_id').val();
    if (!hostel_id) {
        Swal.fire({
            icon: 'warning', // You can change the icon (e.g., 'error', 'info', 'success')
            title: 'Hostel Not Selected',
            text: 'Please select a hostel before searching.',
            confirmButtonText: 'OK' // Customize the button text
        });
        return;  // Prevent the function from proceeding if no hostel is selected
    }

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

    let columns = [];
    let columnHeaders = [];

    if (selectedColumns.includes('student_name')) {
        columns.push({ data: 'student_name', name: 'student_name' });
        columnHeaders.push('Student Name');
    }
    if (selectedColumns.includes('student_id')) {
        columns.push({ data: 'student_id', name: 'student_id' });
        columnHeaders.push('Student ID');
    }
    if (selectedColumns.includes('hostel_room_id')) {
        columns.push({ data: 'hostel_room_id', name: 'hostel_room_id' });
        columnHeaders.push('Room No');
    }
    if (selectedColumns.includes('guardian_contact')) {
        columns.push({ data: 'guardian_contact', name: 'guardian_contact' });
        columnHeaders.push('Guardian Contact');
    }
    if (selectedColumns.includes('room_type_id')) {
        columns.push({ data: 'room_type_id', name: 'room_type_id' });
        columnHeaders.push('Room Type');
    }
    if (selectedColumns.includes('cost')) {
        columns.push({ data: 'cost', name: 'cost' });
        columnHeaders.push('Cost Per Bed');
    }

    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;
    $('#hostel_table 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) {
        // Show a warning message if no data is available
        Swal.fire({
            icon: 'warning',
            title: 'No Data Available',
            text: 'There is no data available to print.',
            confirmButtonText: 'OK'
        });
        return; // Exit the function if there's no data
    }

    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 currentDate = new Date().toLocaleDateString(); // Get current date in default format

    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('<h3 style="margin: 0;">Hostel Wise Report</h3>');
    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: 50%;border: none !important;padding: 0px;"> <strong>Hostel: </strong>' + hostelName + '</td>');
    printWindow.document.write('<td style="text-align: right; width: 50%;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);
}




</script>
@endsection
