@extends('layout.app')

@section('content')
    <div class="card">
        <div class="card-body">
            <form method="post" id="searchForm">
                @csrf
                @method('post')
                <div class="row">
                    @if ($reseller)
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Select Manager</label>
                                <select name="reseller" id="reseller" class="form-control form-control-sm select2">
                                    <option value="">Select One</option>
                                    @foreach ($reseller as $r)
                                        <option value="{{ $r->id }}">{{ $r->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    @endif

                    @if ($poplist)
                        <div class="col-md-4">
                            <label> Select POP </label>
                            <select name="pop" id="pop" class="form-control form-control-sm select2">
                                <option value=""> Select One</option>
                                @foreach ($poplist as $r)
                                    <option value="{{ $r->id }}">{{ $r->popname }}</option>
                                @endforeach
                            </select>
                        </div>
                    @else
                        <div class="col-md-4">
                            <label> Select POP </label>
                            <select name="pop" id="pop" class="form-control form-control-sm select2">
                                <option value=""> Select One</option>
                            </select>
                        </div>
                    @endif
                    @if (checkAPI())
                        <div class="col-md-4">
                            <label>Status</label>
                            <select name="clients_status" id="clients_status" class="form-control form-control-sm select2">
                                <option value="">Select One</option>
                                <option value="active">Active</option>
                                <option value="expired">Expire</option>
                                <option value="deactive">Deactive</option>
                                <option value="disable">Disable</option>
                            </select>
                        </div>
                    @endif
                </div>
                <div class="col-md-12 d-flex justify-content-end align-items-end mt-3">
                    <div class="form-group float-right mt-4">
                        <button class="btn btn-primary" type="submit" id="searchBtn"><i class="fa fa-search"></i> Search</button>
                        <button class="btn btn-info" type="reset" id="reset">Reset</button>

                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="row">
        <div id="result" class="table-responsive">
            <!-- Table will be loaded here -->
        </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;
        }
        .dt-buttons {
            margin-bottom: 10px;
        }

        .dataTables_filter {
            padding-top: 10px;
            padding-right: 10px;
        }
        .dataTables_length select {
            width: 60px !important;  /* Adjust this value as needed */
            min-width: auto;
            display: inline-block;
            margin: 0 5px;
            padding-top: 10px;
            padding-left: 10px;
        }
        .br-spacer {
            height: 10px;
        }
    </style>
@endsection

@section('ajax')
<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">

<!-- DataTables JS -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></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();

            $.ajax({
                type: 'get',
                url: '{{ route('oflineCustomerResult') }}',
                data: $('#searchForm').serialize(),
                success: function(result) {
                    $('#result').html(result);
                    initializeDataTable();
                    $("#loader").hide();
                },
                error: function(xhr, status, error) {
                    $("#loader").hide();
                    var errorMessage = xhr.responseJSON?.message || "An error occurred while processing your request.";
                    toastr.error(errorMessage, "Error");
                }
            });
        });

        $('#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();
                }
            });
        });

        function initializeDataTable() {
            // Destroy any existing DataTable instance first
            if ($.fn.DataTable.isDataTable('#dataTable')) {
                $('#dataTable').DataTable().destroy();
            }

            var table = $('#dataTable').DataTable({
                dom: '<"top"lfB><"br-spacer">rt<"bottom"ip><"clear">',
                buttons: [
                    {
                        extend: 'csv',
                        text: '<i class="fa fa-file-csv"></i> CSV',
                        className: 'btn btn-success btn-sm',
                        title: 'Offline_Customers_' + new Date().toISOString().slice(0, 10),
                        exportOptions: {
                            columns: ':visible',
                            modifier: {
                                page: 'all'
                            }
                        },
                        action: function(e, dt, button, config) {
                            // Get the CSV data
                            var csv = dt.buttons.exportData(config.exportOptions);
                            var csvContent = '';

                            // Add headers
                            if (csv.header.length > 0) {
                                csvContent += csv.header.join(',') + '\n';
                            }

                            // Add CSV data rows
                            csvContent += csv.body.join('\n');

                            // Add UTF-8 BOM for proper Bengali text display in Excel
                            var BOM = '\uFEFF';
                            var finalCsv = BOM + csvContent;

                            // Create and download the file
                            var blob = new Blob([finalCsv], { type: 'text/csv;charset=utf-8;' });
                            var link = document.createElement('a');
                            var url = URL.createObjectURL(blob);
                            link.setAttribute('href', url);
                            var filename = config.title ? config.title.replace(/[^a-z0-9]/gi, '_') : 'Offline_Customers_' + new Date().toISOString().slice(0, 10);
                            link.setAttribute('download', filename + '.csv');
                            link.style.visibility = 'hidden';
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        }
                    }
                ],
                responsive: true,
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                pageLength: 25,
                initComplete: function() {
                    // Hide the default DataTables button and use our custom button
                    $('.dt-buttons').hide();
                }
            });

            // Trigger CSV export when our custom button is clicked
            $(document).on('click', '#downloadCsv', function() {
                table.button('.buttons-csv').trigger();
            });
        }
    });
</script>


@endsection
