@extends('layouts.master')

@push('css')
    <style>
        .tborder {
            border: 1px solid black !important;
        }

        table.customtble tbody tr td {
            padding: 0px 5px;
            font-size: 11px;
        }

        table.customtble thead tr th {
            padding: 0px 5px;
            font-size: 12px;
            font-weight: bold;
        }

        @media print {

            table.customtble thead tr th,
            table.customtble tbody tr td {
                font-size: 10px;
            }

            body * {
                visibility: hidden;
            }

            .printableArea,
            .printableArea * {
                visibility: visible !important;
            }

            table {
                border-collapse: collapse;
            }
        }
    </style>
@endpush

@section('content')
    <div class="printableArea card p-3" id="printableArea">
        <form id="FormId" method="POST" action="{{ route('ageingSummary') }}">
            @csrf
            <div class="row hidden-print">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="r_type">Report Type</label>
                        <select class="form-control" name="report_type" id="r_type">
                            <option value="Receivable">Receivable</option>
                            <option value="Payable">Payable</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-2">
                    <button id="submitbutton" type="button" class="btn btn-primary">
                        <i class="fa fa-search"></i> Run
                    </button>
                </div>
                <div class="col-md-2">
                    <span class="spin-loader"></span>
                </div>
            </div>
        </form>

        <div class="row">
            <div class="col-md-12">
                <h3 class="text-center">Ageing Summary</h3>
                <div class="table-responsive">
                    <table id="tblreport" class="display nowrap table-bordered" style="width: 100%;">
                        <thead>
                            <tr>
                                <th class="text-center">Customer ID</th>
                                <th class="text-center">Customer Name</th>
                                <th class="text-center">Total</th>
                                <th class="text-center">1 - 30</th>
                                <th class="text-center">31 - 60</th>
                                <th class="text-center">61 - 90</th>
                                <th class="text-center">Over 90</th>
                                <th class="text-center">Previous Balance</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td colspan="8" class="text-center">Data not found</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

        <script>
            $(document).ready(function() {
                $('#submitbutton').click(function(e) {
                    e.preventDefault(); // Prevent default button behavior if inside a form

                    // Show loader
                    $('.spin-loader').addClass('fa fa-spin fa-spinner');

                    // Perform AJAX request
                    $.ajax({
                        type: 'POST',
                        url: "{{ route('ageingSummaryData') }}", // Laravel route for the backend
                        data: {
                            report_type: $('#r_type').val(), // Get the selected report type
                            fromdate: '{{ $fromdate ?? '' }}', // Optional parameter if available
                            _token: '{{ csrf_token() }}' // Laravel CSRF token
                        },
                        dataType: 'json', // Expect JSON response
                        beforeSend: function() {
                            console.log("Request is being sent...");
                        },
                        success: function(response) {
                            // Clear existing table body
                            let tbody = $('#tblreport tbody');
                            tbody.empty();

                            // Check if response has data
                            if (response && response.length > 0) {
                                response.forEach(row => {
                                    tbody.append(`
                            <tr>
                                <td class="text-center">${row.customer_id}</td>
                                <td class="text-center">${row.customer_name}</td>
                                <td class="text-center">${row.total}</td>
                                <td class="text-center">${row.range_1_30}</td>
                                <td class="text-center">${row.range_31_60}</td>
                                <td class="text-center">${row.range_61_90}</td>
                                <td class="text-center">${row.range_over_90}</td>
                                <td class="text-center">${row.previous_balance}</td>
                            </tr>
                        `);
                                });
                            } else {
                                // Display "no data" message
                                tbody.append(
                                    '<tr><td colspan="8" class="text-center">No data found</td></tr>'
                                    );
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error("AJAX Error: ", error);
                            console.error("Response Status: ", status);
                            console.error("XHR Response: ", xhr.responseText);
                            alert('Error fetching data. Please check console for details.');
                        },
                        complete: function() {
                            // Hide loader
                            $('.spin-loader').removeClass('fa fa-spin fa-spinner');
                            console.log("Request completed.");
                        }
                    });
                });
            });
        </script>
    @endpush
@endsection
