@extends('layout.app')
@section('content')
    @include('clients.reseller_pop_search')

    <div class="mt-2 card">
        <div class="card-body result">
            <div class="row">
                <div class="col-md-6 pagination">
                    {{ $list->onEachSide(1)->links() }}
                </div>

                <div class="col-md-4">
                    @if (isset($print_url) && !empty($print_url))
                        <a href="{{ route($print_url) }}" target="_blank"><i class="fa fa-print"></i></a>
                    @endif
                </div>
            </div>

            <div id="processing">
                <div>Processing.....</div>
            </div>

            <div id="customer_list_body">
                @include('clients.customer_search')
            </div>

        </div>

        <div class="modal fade" id="billCycleChange">
            <div class="modal-dialog">

                <form action="{{ route('userBillingCycleChange') }}" method="POST" class="flex flex-wrap">
                    @csrf
                    <input type="hidden" name="id" id="bill_client_id">
                    <p id="cid"></p>

                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="text-center">Bill Cycle Change </h4>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <div class="text-center" id="modalAlert"></div>

                            <div class="row">
                                <input type="hidden" id="uuid" name="uuid" value="{{ createUUID() }}">
                                <div class="col-md-4">Select Date</div>
                                <div class="col-md-8 mb-2">
                                    <select name="billCycle" id="allBillCycle" class="form-control" required>
                                        <option value="">Select Date</option>
                                        @foreach (explode(',', $confday) as $item)
                                            <option value="{{ $item }}">
                                                {{ $item }}</option>
                                        @endforeach


                                    </select>
                                </div>

                            </div>


                        </div>
                        <div class="modal-footer justify-content-between">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button class="btn btn-primary" type="submit" id="modalSave">Change</button>
                        </div>
                    </div>
                </form>
            </div>

        </div>

    </div>

    <style>
        div#processing {
            display: none;
        }

        div#processing div {
            background: rgba(0, 0, 0, .5);
            position: fixed;
            width: 100vw;
            height: 100vh;
            color: #fff;
            text-align: center;
            vertical-align: middle;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        @media print {
            a {
                text-decoration: none !important;
                color: #222 !important;
            }

            th {
                font-size: 10px !important;
                padding: 2px !important;
                text-align: center;
            }

            tr {
                font-size: 10px !important;
                margin: 2px !important;
                padding: 2px !important;
            }

            td {
                font-size: 10px !important;
                margin: 2px !important;
                padding: 2px !important;
            }

            table {
                width: 100%;
            }

            .shadow {
                box-shadow: none;
            }

            tr th:last-child {
                display: none !important;
            }

            tr td:last-child {
                display: none !important;
            }

        }
    </style>
@endsection

@section('ajax')
    <script>
        $(function() {

            @if ($close == true)
                if (!$.fn.DataTable.isDataTable('#dataTable')) {
                    $('#dataTable').DataTable({
                        order: [
                            [{{ ($multiple_client_restore ?? false) ? 1 : 0 }}, 'desc']
                        ],
                    });
                }
                @if ($multiple_client_restore ?? false)
                $(document).on('change', '#closeListSelectAll', function() {
                    $('.close-list-restore-id').prop('checked', this.checked);
                });
                $(document).on('click', '#batchRestoreBtn', function() {
                    var ids = [];
                    $('.close-list-restore-id:checked').each(function() {
                        ids.push(parseInt($(this).val(), 10));
                    });
                    if (ids.length === 0) {
                        toastr.warning('Please select at least one client to restore.');
                        return;
                    }
                    var btn = $(this);
                    btn.prop('disabled', true);
                    $.ajax({
                        url: '{{ route("clients.batchRestore") }}',
                        type: 'POST',
                        data: {
                            _token: '{{ csrf_token() }}',
                            ids: ids
                        },
                        success: function(data) {
                            toastr.success(data.message || data.restored + ' client(s) restored.');
                            $('.close-list-restore-id:checked').closest('tr').remove();
                            $('#closeListSelectAll').prop('checked', false);
                            if (typeof $('#dataTable').DataTable === 'function' && $.fn.DataTable.isDataTable('#dataTable')) {
                                $('#dataTable').DataTable().draw(false);
                            }
                        },
                        error: function(xhr) {
                            var msg = xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : 'Restore failed.';
                            toastr.error(msg);
                        },
                        complete: function() {
                            btn.prop('disabled', false);
                        }
                    });
                });
                @endif
            @endif

            $('.clientBillCycleChange').on('click', function() {
                var id = $(this).attr('data-id');
                var billcycle = $(this).attr('data-curdate');


                $("select#allBillCycle option").each(function() {

                    if ($(this).val() == billcycle) { // EDITED THIS LINE
                        $(this).attr("selected", "selected");
                    }
                });


                $('#bill_client_id').val(id);

            });
        })
        var typingTimer; //timer identifier
        var doneTypingInterval = 5000; //time in ms (5 seconds)

        $('#customer_search').on('keyup', function() {
            clearTimeout(typingTimer);
            let name = $(this).val();
            $('#processing').show();

            if (name.length >= 3 || name.length == 0) {
                $.ajax({
                    type: 'get',
                    url: '{{ route('customer_search') }}',
                    data: {
                        search: name
                    },
                    success: function(result) {

                        $('#customer_list_body').html(result);

                        $('#processing').hide();
                        //checkExpire();
                    }
                });
            }


        });
    </script>


    <script type="text/javascript">
        $(function() {
            $('#reset').click(function() {
                $('#result').html('');
                $('#pop').html('<option value="all">Select One</option>');
            });

            $('#searchBtn').on('click', function(e) {
                e.preventDefault();
                $('#loader').show();
                $('.pagination').hide();
                $.ajax({
                    type: 'get',
                    url: '{{ route($search_url) }}',
                    data: $('#search').serialize(),
                    success: function(result) {
                        if (result.status == 'error') {
                            toastr.error(result.message);
                            $('#loader').hide();
                        } else {
                            $('#result').html(result);
                            $('#dataTable').DataTable({
                                destroy: true,
                                pageLength: 100,
                                order: [
                                    [0, 'desc']
                                ], // keep newest rows first (matches controller)
                            });
                            $('#loader').hide();
                        }
                    }
                });
            });




            $('#reseller').on('change', function(e) {
                e.preventDefault();
                $('body').append('<div class="hidden" id="processing">processing.....</div>');

                $.ajax({
                    type: 'get',
                    url: '{{ route('getResellerPopList') }}',
                    data: {
                        id: $(this).val()
                    },
                    success: function(result) {
                        $('#pop').html(result);
                        $('#processing').remove();
                    }
                });
            });

            $('#summaryReportBtn').on('click', function() {
                var from = $('input[name="from_date"]').val();
                var to = $('input[name="to_date"]').val();
                if (!from || !to) {
                    toastr.warning('Please select from date and to date');
                    return;
                }
                var url = '{{ route("newJoinSummaryReport") }}?' + $('#search').serialize();
                window.open(url, '_blank');
            });

        });
    </script>
    <script>
        function export2csv() {
            let data = "";
            const tableData = [];
            const rows = document.querySelectorAll("table#dataTable tr");
            for (const row of rows) {
                const rowData = [];
                for (const [index, column] of row.querySelectorAll("th, td").entries()) {
                    // To retain the commas in the "Description" column, we can enclose those fields in quotation marks.
                    if ((index + 1) % 3 === 0) {
                        rowData.push('"' + column.innerText + '"');
                    } else {
                        // rowData.push(column.innerText);
                        rowData.push(column.innerText.replace(/[\r\n,]/gm, ' '));
                    }
                }
                tableData.push(rowData.join(","));
            }
            data += tableData.join("\n");
            const a = document.createElement("a");
            a.href = URL.createObjectURL(new Blob([data], {
                type: "text/csv"
            }));
            a.setAttribute("download", "data.csv");
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    </script>
@endsection
