@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" multiple>
                                <option value="all" selected>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;max-width:100px">Mobile</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;">Current Balance</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>
                            {{-- <th style="padding-left: 2px;padding-right: 2px;max-width:100px">Date</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" selected> 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('advanced-balanced-customer-search') }}',
                    data: $('#search').serialize(),

                    success: function(result) {

                        let clients = result.clients;
                        var size = Object.keys(clients).length;
                        $("#result_table  tbody"). empty();
                        clients.forEach(element => {

                            var status_class = '';
                            if(element.deleted_at != null || element.clients_status == "expired"){
                                status_class = "bg-danger"

                            }else if(element.clients_status == 'deactive'){
                                status_class = "bg-secondary"
                            }else if(element.clients_status == 'disable'){
                                status_class = "bg-warning"
                            }else{
                                status_class = "bg-success"
                            }
                            let due_amount = 0;
                            if(element.customer_account){

                                due_amount = parseFloat(element.customer_account.dueAmount) * (-1);
                            }else{
                                due_amount = 0;
                            }
                            let sub_package = '';
                            if(element.subpack && result.sub_package_permission == true){
                                sub_package = element.subpack.name;
                            }
                            let main_package = '';
                            if(element.packages && result.mother_packge_permissin == true){
                                main_package = element.packages.package_name;
                            }
                            let address = '';
                            if (element.clientsinfo.flat_no)
                            {
                                address = 'Flat No: '+element.clientsinfo.flat_no+'';
                            }
                            if (element.clientsinfo.building_name)
                            {
                                address += '<br>Building Name: '+element.clientsinfo.building_name+'';
                            }
                            if (element.clientsinfo.road_no)
                            {
                                address += '<br>Road No : '+element.clientsinfo.road_no+'';
                            }

                            if (element.clientsinfo.block_sector)
                            {
                                address += '<br>Block/Sector : '+element.clientsinfo.block_sector+'';
                            }
                            if (element.clientsinfo.area)
                            {
                                address += '<br>Area : '+element.clientsinfo.area+'';
                            }
                            if (element.clientsinfo.box)
                            {
                                address += '<br>Box : '+element.clientsinfo.box+'';
                            }
                            let join_date;
                            if(element.clientsinfo.joinDate){
                                join_date = element.clientsinfo.joinDate;
                            }else{
                                join_date = '';
                            }
                            total_due += parseFloat(due_amount);
                            url = "{{ url('admin/getPaymentHistory') }}"+"/"+element.id;

                            $('#result_table tbody').append('<tr >' +
                                '<td style="padding-left: 2px;padding-right: 2px;"><a class="btn btn-info btn-block btn-xs text-nowrap"'+
                                        'href="'+url+'">CID: '+element.id+'</a></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;">'+element.userid+'<br>'+element.password+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;" class='+status_class+'>'+element.clients_status+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;max-width:100px" class='+status_class+'>'+element.expire_date.split(' ')[0]+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;max-width:150px" >'+element.clientsinfo.clients_name+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;max-width:150px" >'+element.clientsinfo.contact_no+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px;text-align:center" >'+element.billing_cycle+'</td>' +

                                '<td style="padding-left: 2px;padding-right: 2px;max-width:200px" >'+sub_package+'<br>'+main_package+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+due_amount+'</b></td>' +
                                '<td style="padding-left: 4px;padding-right: 2px;" >'+element.pop.popname+'</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>'
                                );

                        });
                        $('#result_table tbody').append('<tr >' +

                                '<td colspan="7" 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)+'</b></td>' +

                                '</tr>'
                                );

                        $('#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", "advanced_balanced_customer_list.csv");
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    </script>

@endsection
