@extends('layouts.master')
@section('content')
@include('report.library.header-menu', ['active_header' => 'book-due-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">
                        <input type="text" id="reportrange" name="date" class="form-control">
                    </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="booklist_id" id="booklist_id" checked style="display:none;">
                            <label class="column-form-check-label" for="booklist_id">Book Title</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="book_number" id="book_number" checked style="display:none;">
                            <label class="column-form-check-label" for="book_number">Book Number</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="issue_date" id="issue_date" checked style="display:none;">
                            <label class="column-form-check-label" for="issue_date">Issue Date</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="estimate_return_date" id="estimate_return_date" checked style="display:none;">
                            <label class="column-form-check-label" for="estimate_return_date">ERD</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="created_by" id="created_by" checked style="display:none;">
                            <label class="column-form-check-label" for="created_by">Issue By</label>
                        </div>
                        <div class="form-check">
                            <input type="checkbox" class="toggle-column column-form-check-input" value="user_id" id="user_id" checked style="display:none;">
                            <label class="column-form-check-label" for="user_id">Member Type</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="book-issue">
                    <thead class="thead-light">
                        <tr>
                            <th>Book Title</th>
                            <th>Book Number</th>
                            <th>Issue Date</th>
                            <th title="estimate return date">ERD</th>
                            <th>Issue By</th>
                            <th>Member Type</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 date = $('#reportrange').val();

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

        $.ajax({
            url: '{{ route("library-book-due-pdf-export") }}', // Route to handle PDF generation
            method: 'POST',
            data: {
                _token: '{{ 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 = 'library.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 date = $('#reportrange').val();

        let selectedColumns = [];
        $('.toggle-column:checked').each(function () {
            selectedColumns.push($(this).val());
        });
        $.ajax({
            url: '{{ route("library-book-due-excel-export") }}',
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}', // Include CSRF token
                'date'   : date,
                '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 = 'library.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
        $('#booklist_id').prop('checked', true);
        $('#book_number').prop('checked', true);
        $('#issue_date').prop('checked', true);
        $('#estimate_return_date').prop('checked', true);
        $('#created_by').prop('checked', true);
        $('#user_id').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
    function viewTable(){
        // Get filter data
        let date = $('#reportrange').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: 'booklist_id', name: 'booklist_id', searchable: true });
        columnHeaders.push('Book Title');
     
        if(selectedColumns.includes('book_number')) {
            columns.push({ data: 'book_number', name: 'book_number',  });
            columnHeaders.push('Book Number');
        }
        if(selectedColumns.includes('issue_date')) {
            columns.push({ data: 'issue_date', name: 'issue_date',  });
            columnHeaders.push('Issue Date');
        }
        if(selectedColumns.includes('estimate_return_date')) {
            columns.push({ data: 'estimate_return_date', name: 'estimate_return_date',  });
            columnHeaders.push('ERD');
        }
        if(selectedColumns.includes('created_by')) {
            columns.push({ data: 'created_by', name: 'created_by',  });
            columnHeaders.push('Issue By');
        }
        if(selectedColumns.includes('user_id')) {
            columns.push({ data: 'user_id', name: 'user_id',  });
            columnHeaders.push('Member Type');
        }

        // 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('#book-issue')) {
                $('#book-issue').DataTable().clear().destroy();
            }

            // Initialize DataTable with no columns
            table = $('#book-issue').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('library-book-due-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('#book-issue')) {
                $('#book-issue').DataTable().clear().destroy();
            }
            // Rebuild table headers
            const thead = $('#book-issue').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('#book-issue')) {
                $('#book-issue').DataTable().clear().destroy();
            }

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


    // print function
    function printTable(){
        let reportrange = $('#reportrange').val();
        // alert(reportrange);
        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('booklist_id')) {
            columns.push({ data: 'booklist_id', name: 'booklist_id',  });
            columnHeaders.push('Book Title');
        }
        if(selectedColumns.includes('book_number')) {
            columns.push({ data: 'book_number', name: 'book_number',  });
            columnHeaders.push('Book Number');
        }
        if(selectedColumns.includes('issue_date')) {
            columns.push({ data: 'issue_date', name: 'issue_date',  });
            columnHeaders.push('Issue Date');
        }
        if(selectedColumns.includes('estimate_return_date')) {
            columns.push({ data: 'estimate_return_date', name: 'estimate_return_date',  });
            columnHeaders.push('ERD');
        }
        if(selectedColumns.includes('created_by')) {
            columns.push({ data: 'created_by', name: 'created_by',  });
            columnHeaders.push('Issue By');
        }
        if(selectedColumns.includes('user_id')) {
            columns.push({ data: 'user_id', name: 'user_id',  });
            columnHeaders.push('Member Type');
        }

        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;
        $('#book-issue 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 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('<p style="margin: 0;"><strong>Book Due 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: 50%;border: none !important;padding: 0px;"> <strong>Filter By: </strong>' + reportrange + '</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);
    }


// 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('booklist_id')) {
            columns.push({ data: 'booklist_id', name: 'booklist_id',  });
            columnHeaders.push('Book Title');
        }
        if(selectedColumns.includes('book_number')) {
            columns.push({ data: 'book_number', name: 'book_number',  });
            columnHeaders.push('Book Number');
        }
        if(selectedColumns.includes('issue_date')) {
            columns.push({ data: 'issue_date', name: 'issue_date',  });
            columnHeaders.push('Issue Date');
        }
        if(selectedColumns.includes('estimate_return_date')) {
            columns.push({ data: 'estimate_return_date', name: 'estimate_return_date',  });
            columnHeaders.push('ERD');
        }
        if(selectedColumns.includes('created_by')) {
            columns.push({ data: 'created_by', name: 'created_by',  });
            columnHeaders.push('Issue By');
        }
        if(selectedColumns.includes('user_id')) {
            columns.push({ data: 'user_id', name: 'user_id',  });
            columnHeaders.push('Member Type');
        }

        // 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>';
        // tableContent += '<tr>';
            $('#book-issue tbody tr').each(function() {
            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>';
        });
        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>Library Report:</strong> Book Issue Report</h1>');
        printWindow.document.write(tableContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.print();
    }
</script>
@endsection