@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">
                                Select Type
                            </label>
                            <select id="type" name="type" class="form-control select2 form-control-sm" required
                                style="width: 100% !important;">
                                <option value="">Select One</option>
                                <option value="month">Month wise Due</option>
                                <option value="batch">Genarally Due</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3 col-sm-3 col-xs-6 manager" style="display: none">
                        <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 pop" style="display: none">
                        <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 area" style="display: none">
                        <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 bill" style="display: none">
                        <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 class="col-md-3 col-sm-3 col-xs-6 status" style="display: none">
                        <div class="form-group">
                            <label class="flex-1 block text-gray-700 text-sm font-bold mb-2">
                                Select Close Status
                            </label>
                            <select name="close_status" id="close_status" class="select2 form-control form-control-sm">
                                <option value="closed" selected>With Closed</option>
                                <option value="notClosed">With Out Closed</option>

                            </select>

                        </div>
                    </div>
                    <div class="col-md-3 col-sm-3 col-xs-6 from" style="display: none">
                        <label class="block text-gray-700 text-sm font-bold mb-2" for="from_date">
                            From Date
                        </label>
                        <div class="input-group date" id="searchFrom" data-target-input="nearest">
                            <input type="text" name="from_date"
                                class="form-control datetimepicker-input input-group-append" data-toggle="datetimepicker"
                                data-target="#searchFrom" autocomplete="off">

                        </div>
                    </div>

                    <div class="col-md-3 col-sm-3 col-xs-6 to" style="display: none">
                        <div class="form-group">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="to_date">
                                To Date
                            </label>
                            <div class="input-group date" id="searchTo" data-target-input="nearest">
                                <input type="text" name="to_date"
                                    class="form-control datetimepicker-input input-group-append"
                                    data-toggle="datetimepicker" data-target="#searchTo" autocomplete="off">
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3 col-sm-3 col-xs-6 due" style="display: none">
                        <div class="form-group">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="due">
                                Due Type
                            </label>
                            <select name="due_type" id="due_type" class="form-control">
                                <option value="full_due" selected>All Due</option>
                                <option value="partial_due">Partial Due</option>

                            </select>
                        </div>
                    </div>


                </div>
                <div class="form-group float-right">
                    <button class="btn btn-primary" type="submit" id="searchBtnDue"><i class="fa fa-search"></i>
                        Search</button>
                    <a class="btn " href="{{ route('due-customer') }}" style="background: #f87171; color:#FFFFFF;">Reset</a>
                </div>

            </form>

        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="w-100 d-flex  justify-content-between p-1 flex-directions" >

                   <div id="downloadFile" class="d-none">
                    <button class="btn  w-100 " onclick="export2csv()" style="background: #a21caf;color:#FFFFFF;">Download csv</button>
                   </div>

                <div class="mt-2 mb-2 text-center  d-none flex-directions" id="totalContainer">
                     <p class="border border-warning rounded p-1">Total Due
                        Amount <span>:</span>
                        <span id="total_amount_show"></span>
                     </p>

                         <p class="border border-warning rounded p-1">
                            Total Customer <span>:</span>
                         <span id="total_customer"></span>
                         </p>
                 </div>

            </div>

            <div id="result" class="table-responsive">
                <table class="table table-striped table-bordered table-condensed" id="result_table">
                    <thead style="background:#78716c;color:#FFFFFF;">
                        <tr class="text-center">

                            <th>ID</th>
                            <th style="padding-left: 2px;padding-right: 2px;">User name</th>
                            <th class="status">Status</th>
                            <th class="status">Expire</th>
                            <th>Name</th>
                            <th>Mobile</th>
                            <th>Billing Cycle</th>
                            <th>Package</th>
                            <th>POP</th>
                            <th>User Info</th>
                            <th class="text-center">Due Amount</th>

                            {{-- <th style="padding-left: 2px;padding-right: 2px;max-width:100px">Date</th> --}}

                        </tr>
                    </thead>
                    <tbody class="text-center">

                    </tbody>

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


    <style>
        .flex-directions {
            flex-direction: column !important;
        }

        @media(min-width:640px) {
            .flex-directions {
                flex-direction: row !important;
            }
        }
    </style>
@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();

                    }
                });
            });

            function addDays(date, days) {
                date.setDate(date.getDate() + days);
                return date;
            }


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

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

                    success: function(result) {
                        //  console.log(result);
                        var col = 10;
                        let clients = result.clients;
                        var size = 0;
                        var type = result.type;
                        $("#result_table  tbody").empty();
                        clients.forEach(element => {

                            var status_style = '';
                            if (type == 'month') {
                                status_style = "display: none";
                                col = 8;
                            }
                            var status_class = '';
                            var close_status = '';
                            if (element.deleted_at != null) {
                                status_class = "bg-dark"
                                close_status = "Closed";

                            } else if (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.generated_bill) {
                                let client_bill = 0;
                                let client_payment = 0;
                                let bill = element.generated_bill;
                                bill.forEach(billElement => {
                                    if (billElement.bill_amount) {
                                        client_bill += parseFloat(billElement
                                            .bill_amount);
                                    }
                                    if (billElement.paid_amount) {
                                        client_payment += parseFloat(billElement
                                            .paid_amount);
                                    }
                                });
                                due_amount = client_bill - client_payment;
                                // console.log(due_amount);

                            } else {

                                if (element.customer_account) {

                                    due_amount = element.customer_account.dueAmount;
                                } 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;

                            let pd = new Date(element.expire_date);
                            let newDate = addDays(pd, element.payment_dadeline);

                            // 2022-05-20T00:00:00.000Z
                            // console.log(newDate);
                            var permission = "{!! Auth::user()->hasPermissionTo('change-expire-date') ? 'permited' : '' !!}";

                            let expire_date = "";
                            if (element.expire_date) {
                                expire_date = element.expire_date.split(' ')[0];
                            } else {
                                expire_date = '';
                            }
                            let usercid = element.id;
                            if (due_amount > 0) {

                                size++;

                                $('#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; ' +
                                    status_style + '" class=' + status_class + '>' +
                                    element.clients_status + '<br>' + close_status +
                                    (permission == 'permited' ? '<button type="button" class="dropdown-item changeExpireDate badge badge-dark p-1" data-toggle="modal" data-id="'+ usercid +'" data-target="#changeExpireDate">Change</button>' : '') +
                                    '</td>' +
                                    '<td style="padding-left: 2px;padding-right: 2px;max-width:250px; ' +
                                    status_style + '" class=' + status_class +
                                    '> BD: ' + expire_date +
                                    '<br> Extra Payment Day : ' + element
                                    .payment_dadeline + ' day</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: 4px;padding-right: 2px;" >' +
                                    element.pop.popname + '</td>' +
                                    '<td style="padding-left: 2px;padding-right: 2px;max-width:200px; text-align:start;" >' +
                                    address + '</td>' +
                                    '<td style="padding-left: 2px;padding-right: 2px; text-align: center;"  ><b>' +
                                    due_amount + '</b></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>'

                                );
                            }




                        });
                        // console.log(size);
                        $('#result_table tbody').append('<tr >' +

                            '<td colspan="' + col +
                            '" style="padding-left: 2px;padding-right: 2px; text-align: right;" id="customerData"><b>Total(' +
                            size + ')</b></td>' +
                            '<td colspan="" style="padding-left: 2px;padding-right: 2px; text-align: right;" id="amount"><b>' +
                            parseFloat(total_due).toFixed(2) + '</b></td>' +

                            '</tr>'


                        );

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


                        const amount = document.getElementById("amount");
                        const totalCustomerData = document.getElementById("customerData");
                        const totalToShow = document.getElementById("total_amount_show");
                        const totalCustomerToShow = document.getElementById("total_customer");
                        const container = document.getElementById("totalContainer");
                        /*csv*/
                        const csvBtn = document.getElementById("downloadFile");
                        csvBtn.classList.remove("d-none");
                        csvBtn.classList.add("d-inline-block");
                        /*amount and user count*/
                        container.classList.remove("d-none");
                        container.classList.add("d-flex");
                        container.style.columnGap="4px";
                        totalToShow.textContent = amount.textContent;
                        totalCustomerToShow.textContent = totalCustomerData.textContent;

                    }
                });
            });

            $('#type').on('change', function() {

                const container = document.getElementById("totalContainer");
                const csvBtn = document.getElementById("downloadFile");
                container.classList.add("d-none");
                container.classList.remove("d-flex");

                csvBtn.classList.add("d-none");
                csvBtn.classList.remove("d-inline-block");


                let type_val = $('#type').val();

                if (type_val == 'batch') {
                    $('#result_table tbody').empty();

                    $('.manager').show();
                    $('.pop').show();
                    $('.area').show();
                    $('.bill').show();
                    $('.status').show();
                    $('.from').show();
                    $('.to').show();
                    $('.due').hide();
                } else if (type_val == 'month') {
                    $('#result_table tbody').empty();

                    $('.manager').show();
                    $('.pop').show();
                    $('.area').show();
                    $('.bill').hide();
                    $('.status').hide();
                    $('.from').show();
                    $('.to').show();
                    $('.due').show();
                }
            });

        });

        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


<script></script>
