@extends('layout.app')

@section('content')

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

                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <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" value="{{$start->format('m/d/y')}}"
                                    class="form-control datetimepicker-input input-group-append"
                                    data-toggle="datetimepicker" data-target="#searchFrom"
                                    autocomplete="off">

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

                    <div class="col-md-3">
                        <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" value="{{$end->format('m/d/y')}}"
                                    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">
                        <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;max-width:200px; text-align: left;">User Info</th>
                            <th style="padding-left: 2px;padding-right: 2px; text-align: right;">Total Bill Amount</th>
                            <th style="padding-left: 2px;padding-right: 2px; text-align: right;">Due Amount</th>
                            <th style="padding-left: 2px;padding-right: 2px; text-align: right;">Recived Amount</th>
                            <th style="padding-left: 2px;padding-right: 2px; text-align: right;">Discount Amount</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;
                let total_discount_amount = 0;
                let total_paid_amount = 0;
                let total_bill_amount = 0;
                $.ajax({
                    type: 'get',
                    url: '{{ route('recent-customer-account-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 bill_amount = 0;
                            let due_amount = 0;
                            let paid_amount = 0;
                            let discount_amount = 0;
                            if(element.customer_account){
                                bill_amount = element.customer_account.totalBillAmount;
                                due_amount = element.customer_account.dueAmount;
                                paid_amount = element.customer_account.totalPaid;
                                discount_amount = element.customer_account.totalDiscount;
                            }else{
                                due_amount = 0;
                            }

                            let address = '';
                            if(element.subpack){
                                // sub_package = element.subpack.name;
                                address += 'Sub Package: '+element.subpack.name+'<br>';

                            }

                            if(element.packages){
                                // main_package = element.packages.package_name;
                                address += 'Package: '+element.packages.package_name+'<br>';

                            }
                            if(element.pop.popname){
                                address += 'Pop: '+element.pop.popname+'<br>';
                            }
                            if(element.billing_cycle){
                                address += 'Billing cycle: '+element.billing_cycle+'<br>';
                            }
                            if (element.clientsinfo.flat_no)
                            {
                                address += 'Flat No: '+element.clientsinfo.flat_no+'<br>';
                            }
                            if (element.clientsinfo.building_name)
                            {
                                address += 'Building Name: '+element.clientsinfo.building_name+'<br>';
                            }
                            if (element.clientsinfo.road_no)
                            {
                                address += 'Road No : '+element.clientsinfo.road_no+'<br>';
                            }

                            if (element.clientsinfo.block_sector)
                            {
                                address += 'Block/Sector : '+element.clientsinfo.block_sector+'<br>';
                            }
                            if (element.clientsinfo.area)
                            {
                                address += 'Area : '+element.clientsinfo.area+'<br>';
                            }
                            if (element.clientsinfo.box)
                            {
                                address += 'Box : '+element.clientsinfo.box+'<br>';
                            }

                            let join_date;
                            if(element.clientsinfo.joinDate){
                                join_date = element.clientsinfo.joinDate;
                            }else{
                                join_date = '';
                            }
                            total_bill_amount += parseFloat(bill_amount);
                            total_due += parseFloat(due_amount);
                            total_paid_amount += parseFloat(paid_amount);
                            total_discount_amount += parseFloat(discount_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:left" >'+address+'</td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+bill_amount+'</b></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+due_amount+'</b></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+paid_amount+'</b></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+discount_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>'
                                );

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

                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>Total('+size+')</b></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+parseFloat(total_bill_amount).toFixed(2)+'</b></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+parseFloat(total_due).toFixed(2)+'</b></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+parseFloat(total_paid_amount).toFixed(2)+'</b></td>' +
                                '<td style="padding-left: 2px;padding-right: 2px; text-align: right;" ><b>'+parseFloat(total_discount_amount).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()) {

                    rowData.push(column.innerText.replace(/[\r\n]/gm, ' '));
                }
                tableData.push(rowData.join(","));
            }
            data += tableData.join("\n");

            // Add UTF-8 BOM for proper Bengali text display in Excel
            const BOM = "\uFEFF";
            const csvContent = BOM + data;

            const a = document.createElement("a");
            a.href = URL.createObjectURL(new Blob([csvContent], { type: "text/csv;charset=utf-8;" }));
            a.setAttribute("download", "recent_customer_report.csv");
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
    }
    </script>

@endsection
