@extends('backend.layouts.app')

@section('content')
    <style>
        .dt-buttons {
            float: right !important;
        }
    </style>

    <div class="row page-titles">
        <div class="col-md-5 align-self-center">
            <h4 class="text-themecolor">Transaction Manager</h4>
        </div>
        <div class="col-md-7 align-self-center text-right">
            <div class="d-flex justify-content-end align-items-center">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                    <li class="breadcrumb-item active">Transaction Manager</li>
                </ol>
            </div>
        </div>
    </div>

    <div class="container-fluid">
        <div class="content-wrapper">
            <section class="content">
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="col-md-12">
                                    <form action="{{ route('transaction') }}" method="get" id="custom-filter-form">
                                        <div class="align-items-start">
                                            <div class="row">
                                                <div class="col-md-2">
                                                    <label>From Date: &nbsp;</label>
                                                    <div>
                                                        <input class="form-control dateInput mr-3 mb-3" id="from_date"
                                                            name="from_date" type="date" onchange="updateToDate()"
                                                            onkeydown="return false;">
                                                    </div>
                                                </div>
                                                <div class="col-md-2">
                                                    <label>To Date: &nbsp;</label>
                                                    <div>
                                                        <input class="form-control dateInput mr-3 mb-3" id="to_date"
                                                            name="to_date" type="date" disabled
                                                            onkeydown="return false;">
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <label>Plans</label>
                                                    <div>
                                                        <select name="search_name" id="search_name"
                                                            class="form-control select2" multiple>
                                                            @foreach ($plans as $plan)
                                                                <option value="{{ $plan->name }}">{{ $plan->name }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                </div>

                                                <div class="col-md-3">
                                                    <label>Area</label>
                                                    <div>
                                                        <select name="area_id[]" id="area_id" class="form-control select2"
                                                            multiple>
                                                            @foreach ($areas as $area)
                                                                <option value="{{ $area->id }}">
                                                                    {{ $area->code . '-' . $area->name }}</option>
                                                            @endforeach
                                                        </select>

                                                    </div>
                                                </div>

                                                <div class="col-md-2 d-flex gap-2"
                                                    style="margin-top: 1.8rem;margin-bottom: 1rem;">
                                                    <button class="btn btn-sidebar btn btn-secondary w-100" type="submit">
                                                        <i class="fas fa-search fa-fw"></i>
                                                    </button>
                                                    <a href="{{ route('transaction') }}" class="btn btn-secondary w-100"
                                                        title="Reload" id="reset-filter">
                                                        <i class="fas fa-sync"></i>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <br>
                                <div style="text-align:right;">
                                    {{-- <a class="btn btn-primary " href="{{ route('export.transactions') }}">Export List</a> --}}
                                </div>
                                <div class="table-responsive">
                                    <div>
                                        <div class="text-right">
                                            <button style="background-color: #fb9678;
    border-color: #fb9678;"
                                                id="download-invoices" class="btn btn-warning btn-sm">Download
                                                Invoices</button>
                                        </div>
                                        {{ $dataTable->table(['class' => 'table table-bordered table-hover', 'style' => 'width:100%;', 'id' => 'transaction-datatable']) }}
                                        <div>
                                            <label for="goToPageInput">Go to Page:</label>
                                            <input type="number" id="goToPageInput" min="1" style="width: 60px;">
                                            <button id="goToPageBtn" class="btn btn-sm btn-primary">Go</button>
                                        </div>
                                    </div>


                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
@endsection

@push('custom-script')
    {!! $dataTable->scripts() !!}

    <script>
        $(document).ready(function() {
            const table = $('#transaction-datatable');

            // Create the footer if it doesn't exist
            // if (!table.find('tfoot').length) {
            //     table.append(`
        //         <tfoot>
        //             <tr>
        //                 <th colspan="4" class="text-right" >Total:</th>
        //                 <th id="creditSum"></th>
        //                 <th id="debitSum"></th>
        //                 <th colspan="3"></th>
        //             </tr>
        //         </tfoot>
        //     `);
            // }

            calculateTotals(); // Call the function initially

            // Calculate tables when dataTable redraw
            if ($.fn.DataTable.isDataTable('#transaction-datatable')) {
                $('#transaction-datatable').on('draw.dt', function() {
                    calculateTotals();
                });
            }

            // Function to calculate and update the totals
            function calculateTotals() {
                let creditTotal = 0;
                let debitTotal = 0;

                // Iterate through table rows (excluding header and footer)
                table.find('tbody tr').each(function() {
                    const creditValue = parseFloat($(this).find('td:eq(4)').text()) ||
                        0; // Credit column (index 4)
                    const debitValue = parseFloat($(this).find('td:eq(5)').text()) ||
                        0; // Debit column (index 5)
                    creditTotal += creditValue;
                    debitTotal += debitValue;
                });

                // Update the footer cells
                $('#creditSum').html(creditTotal.toFixed(2)); // Format to 2 decimal places
                $('#debitSum').html(debitTotal.toFixed(2));
            }

            var DataaTable = $('#transaction-datatable').DataTable();

            $(document).on('submit', '#custom-filter-form', function(e) {
                e.preventDefault();
                var from_date = $('#from_date').val() || '';
                var to_date = $('#to_date').val() || '';
                var search_name = $('#search_name').val() || '';
                var area_id = $('#area_id').val() || '';

                var params = {
                    from_date: from_date,
                    to_date: to_date,
                    search_name: search_name,
                    area_id: area_id,
                };

                DataaTable.ajax.url("{{ route('transaction') }}?" + $.param(params)).load();
            });

            $(document).on('click', '#reset-filter', function(e) {
                e.preventDefault();
                $('#custom-filter-form')[0].reset();
                $('#to_date').prop('disabled', true);
                var url = "{{ route('transaction') }}";
                DataaTable.ajax.url(url).load();
            });

        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const dateInput = document.getElementById('from_date');
            dateInput.addEventListener('click', function() {
                this.showPicker();
            });
        });
    </script>

    <script>
        function updateToDate() {
            var fromDateInput = document.getElementById('from_date');
            var toDateInput = document.getElementById('to_date');
            var today = new Date().toISOString().split('T')[0];
            fromDateInput.max = today;
            toDateInput.max = today;
            toDateInput.disabled = false;
            toDateInput.min = fromDateInput.value;
            if (toDateInput.value < fromDateInput.value) {
                toDateInput.value = fromDateInput.value;
            }

            toDateInput.addEventListener('click', function() {
                this.showPicker();
            });
        }

        window.onload = function() {
            var fromDateInput = document.getElementById('from_date');
            var toDateInput = document.getElementById('to_date');
            var today = new Date().toISOString().split('T')[0];
            fromDateInput.max = today;
            toDateInput.max = today;
        };
        $(document).ready(function() {
            $('#search_name').select2({
                placeholder: "Select Plan(s)",
                allowClear: true
            });
            $('#area_id').select2({
                placeholder: "Select Area(s)",
                allowClear: true
            });
        });


        $(document).on('change', '#select-all', function() {
            $('.row-checkbox').prop('checked', this.checked);
        });

        $('#download-invoices').on('click', function() {
            let selectedIds = $('.row-checkbox:checked').map(function() {
                return $(this).val();
            }).get();

            if (selectedIds.length === 0) {
                alert('Please select at least one transaction.');
                return;
            }

            // Redirect to bulk download route with selected IDs
            let url = "{{ route('transaction.bulk.invoice.download') }}?ids=" + selectedIds.join(',');
            window.location.href = url;
        });

        $(document).ready(function() {
            var table = $('#transaction-datatable').DataTable();
            $('#goToPageBtn').on('click', function() {
                var pageNumber = parseInt($('#goToPageInput').val(), 10);

                if (!isNaN(pageNumber) && pageNumber > 0 && pageNumber <= table.page.info().pages) {
                    table.page(pageNumber - 1).draw('page');
                } else {
                    alert('Invalid page number');
                }
            });
        });


    </script>
@endpush
