@extends('layout.app')

@section('content')

    <div class="card">
        <div class="card-body">
            <form action="" id="search">

                <div class="row">
                    <div class="col-md-3 col-sm-3 col-xs-6">
                        <div class="form-group">
                            <label class="flex-1 block text-gray-700 text-sm font-bold mb-2" >
                                Manager Name
                            </label>
                            <select name="reseller" id="reseller" class="form-control select2 form-control-sm" required>
                                <option value="all">ALL Manager</option>
                                @foreach ($resellers as $r)
                                    <option value="{{ $r->id }}">{{ $r->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-3 col-xs-6">
                        <div class="form-group">
                            <label class="flex-1 block text-gray-700 text-sm font-bold mb-2" >
                                POP Name
                            </label>
                            <select name="pop" id="pop" class="select2 form-control form-control-sm" >
                                <option value="all"> ALL POP</option>

                            </select>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-3 col-xs-6">
                        <div class="form-group">
                            <label class="flex-1 block text-gray-700 text-sm font-bold mb-2" >
                                Select Area
                            </label>
                            <select name="area" id="area" class="select2 form-control form-control-sm">
                                <option value="all">ALL Area</option>

                            </select>

                        </div>
                    </div>
                    <div class="col-md-3 col-sm-3 col-xs-6">
                        <div class="form-group">
                            <label class="flex-1 block text-gray-700 text-sm font-bold mb-2" >
                                Billing Cycle
                            </label>
                            <select name="billing_cycle" id="billing_cycle" class="select2 form-control form-control-sm">
                                <option value="all">ALL Billing Cycle</option>
                                @foreach (explode(',', $confday) as $conf)
                                    <option value="{{ $conf }}">{{ $conf }}</option>
                                @endforeach

                            </select>

                        </div>
                    </div>


                </div>
                <div class="form-group float-right">
                    <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>

            </form>

        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <button class="btn btn-primary mb-2" onclick="export2csv()">Download csv</button>
            <div id="result">
                <table class="table table-striped table-borderless table-condensed" id="result_table">
                    <thead>
                        <tr class="bg-black">

                            <th style="padding-left: 2px;padding-right: 2px;">ID</th>
                            <th style="padding-left: 2px;padding-right: 2px;">User name</th>
                            <th style="padding-left: 2px;padding-right: 2px;">Status</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:100px">Expire</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:100px">Name</th>
                            <th style="padding-left: 2px;padding-right: 2px;">Billing Cycle</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:200px">Package</th>
                            <th style="padding-left: 2px;padding-right: 2px; text-align: right;">Due Amount</th>
                            <th style="padding-left: 4px;padding-right: 2px;">POP</th>

                            <th style="padding-left: 2px;padding-right: 2px;max-width:200px">User Info</th>
                        </tr>
                    </thead>
                    <tbody>

                    </tbody>

                </table>
            </div>
        </div>
    </div>




@endsection




@section('ajax')
    <script type="text/javascript">
        $(function() {
            $('#reset').click(function() {
                $("#result_table  tbody"). empty();
                $('#pop').html('<option value="all">ALL POP</option>');
                $('#area').html('<option value="all"> All Area </option>');
                $("#reseller").val('all').change();
                $("#billing_cycle").val('all').change();

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

                $.ajax({
                    type: 'get',
                    url: '{{ route('getResellerAreaPop') }}',
                    data: {
                        id: $(this).val()
                    },
                    success: function(result) {

                        $('#pop').empty();
                        $('#pop').append('<option value="all"> All Pop </option>');
                        result.pops.forEach(element => {
                            $('#pop').append('<option value="' + element.id + '">' + element.popname + '</option>');
                        });

                        $('#area').empty();
                        $('#area').append('<option value="all"> All Area </option>');
                        result.areas.forEach(element => {

                            if (element != "") {
                                $('#area').append('<option value="' + element + '">' + element + '</option>');
                            }

                        });

                        $('#loading').remove();

                    }
                });
            });

            $('#searchBtn').on('click', function(e) {
                e.preventDefault();

                $('body').prepend('<div id="loading">Loading.....</div>');
                let total_due = 0;
                $.ajax({
                    type: 'get',
                    url: '{{ route('get-bill-extends-customers') }}',
                    data: $('#search').serialize(),

                    success: function(result) {
                        $("#result_table  tbody"). empty();
                        let hole_data = '';
                        let clients = result.clients;

                        var size = Object.keys(clients).length;

                        for (const [key, value] of Object.entries(clients)) {
                            // check client status and set status class
                            total_due += parseFloat(value['due_amount']);
                            var status_class = '';
                            if(value['deleted_at'] != null || value['status'] == "expired"){
                                status_class = "bg-danger"

                            }else if(value['status'] == 'deactive'){
                                status_class = "bg-secondary"
                            }else if(value['status'] == 'disable'){
                                status_class = "bg-warning"
                            }else{
                                status_class = "bg-success"
                            }
                            // make full address
                            let address = '';
                            if (value['flat_no'])
                            {
                                address = 'Flat No: '+value['flat_no']+'';
                            }
                            if (value['building_name'])
                            {
                                address += '<br>Building Name: '+value['building_name']+'';
                            }
                            if (value['road_no'])
                            {
                                address += '<br>Road No : '+value['road_no']+'';
                            }

                            if (value['block_sector'])
                            {
                                address += '<br>Block/Sector : '+value['block_sector']+'';
                            }
                            if (value['area'])
                            {
                                address += '<br>Area : '+value['area']+'';
                            }
                            if (value['box'])
                            {
                                address += '<br>Box : '+value['box']+'';
                            }
                            if (value['client_latitude'])
                            {
                                address += '<br>Latitude : '+value['client_latitude']+'';
                            }
                            if (value['client_longitude'])
                            {
                                address += '<br>Longitude : '+value['client_longitude']+'';
                            }
                            // create connetion date
                            let connection_date = '';
                            if (value['created_at'])
                            {
                                connection_date += 'CD : '+value['created_at']+'';
                            }
                            if (value['joinDate'])
                            {
                                connection_date += '<br>JD : '+value['joinDate']+'';
                            }
                            // create action
                            let details_url =  "{{ url('admin/clients') }}"+"/"+value['id'];
                            let edit_url =  "{{ url('admin/clients') }}"+"/"+value['id']+"/edit";
                            let action = '<a href="'+details_url+'"  class="btn btn-secondary btn-block btn-xs">Details</a>';
                            if(result.mac_customer_edit_permission == true){
                                action += '<a href="'+edit_url+'" class="btn btn-primary btn-block inline-block btn-xs">Edit</a>';
                            }

                            if(value['status'] == 'deactive' && result.customer_reactivate_permission == true){
                                action += '<button onclick="status('+value['id']+',\'idEnable\')" type="button" class="btn btn-success btn-block btn-xs">Reactive</button>';
                            }

                            if(result.customer_recharge_permission == true && result.id_enable_permission == true && value['status'] != 'deactive' && value['status'] == 'disable' ){
                                action += '<button onclick="status('+value['id']+',\'idEnable\')" type="button" class="btn btn-success btn-block btn-xs">Enable</button>';
                            }

                            if(result.customer_recharge_permission == true && result.id_disable_permission == true && value['status'] != 'deactive' && value['status'] != 'disable'){
                                action += '<button onclick="status('+value['id']+',\'idDIsable\')" type="button" class="btn btn-warning btn-block btn-xs">Disable</button>';
                            }

                            if(result.customer_recharge_permission == true && result.customer_deactivated_permission == true && value['status'] != 'deactive' ){
                                action += '<button onclick="status('+value['id']+',\'idDeactive\')" type="button" class="btn btn-danger btn-block btn-xs">Deactive</button>';
                            }

                            hole_data += '<tr >' +

                                '<td style="padding-left: 2px;padding-right: 2px;">'+value['id']+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;">'+value['user_id']+'<br>'+value['password']+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;" class='+status_class+'>'+value['status']+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;max-width:130px" class='+status_class+'>BD: '+value['expire_date']+'<br>PD: '+value['payment_dadeline']+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;max-width:150px" >'+value['name']+'<br>'+value['contact_no']+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;text-align:center" >'+value['billing_cycle']+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;max-width:200px" ><span class="badge badge-info">'+value['sub_package']+'</span><br><span class="badge badge-info">'+value['mother_package']+'</span></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;max-width:200px;text-align: right;" >'+value['due_amount']+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;text-align: center" >'+value['pop_name']+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;max-width:200px" >'+address+'</td>' +

                                // '<td style="padding-left: 2px;padding-right: 2px;max-width:100px" >CD:<br>'+element.created_at.split('T')[0]+'<br>JD:<br>'+join_date.split('T')[0]+'</td>' +
                                '</tr>';
                        }
                        hole_data += '<tr >' +
                            '<td colspan="6" style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>Total('+size+')</b></td>' +
                            '<td colspan="2" style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+parseFloat(total_due).toFixed(2)+' Taka</b></td>' +
                            '</tr>';
                        $("#result_table  tbody").append(hole_data);

                        $('#loading').remove();
                        }
                });
            });
        });
        function export2csv() {
            let data = "";
            const tableData = [];
            const rows = document.querySelectorAll("table#result_table 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", "due_list.csv");
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    </script>

@endsection
