@extends('layout.app')
@section('content')
    <div class="card">
        <div class="card-body">
            <div class="form-group">
                <a class="noprint btn btn-primary"
                    href="{{ route('billSheet') }}?type={{ request()->type }}&search={{ request()->search }}&print=true&due=yes&sortBy={{ request()->get('sortBy') }}"
                    target="_blank">
                    <i class="fa fa-print"></i> Print with Due
                </a>
                <a class="noprint btn btn-primary"
                    href="{{ route('billSheet') }}?type={{ request()->type }}&search={{ request()->search }}&print=true&due=no&sortBy={{ request()->get('sortBy') }}"
                    target="_blank">
                    <i class="fa fa-print"></i> Print without Due
                </a>

                <button class="btn btn-primary" onclick="export2csv()">Download csv</button>
                <a href="{{ route('all-invoice-pdf') }}?type={{ request()->type }}&search={{ request()->search }}&sortBy={{ request()->get('sortBy') }}">
                    <button class="btn btn-primary">Print Invoice</button>
                </a>

                <a href="#" class="noprint btn btn-info">Total Customer: {{ $list->count() }}</a>
                {{-- <a href="#" class="noprint btn btn-info">Total Due Amount: {{ $list->sum('dueAmount') }}</a> --}}
                <a href="#" class="noprint btn btn-info">Total Due Amount: {{ $list->where('dueAmount', '>', 0)->sum('dueAmount') }}</a>
                <div class="">

                    <div class="row mt-2">
                        <div class="form-group col-md-3">
                            <label>Sort by :</label>
                            <select name="sortBy" id="sortBy" class="form-control form-control-sm">
                                <option value="">Default</option>
                                <option value="id" @if(request()->get('sortBy')=='id') selected @endif>CID</option>
                                <option value="userid" @if(request()->get('sortBy')=='userid') selected @endif>Username</option>
                                <option value="code" @if(request()->get('sortBy')=='code') selected @endif>Customer Code</option>
                                <option value="area" @if(request()->get('sortBy')=='area') selected @endif>Area</option>
                                <option value="pop" @if(request()->get('sortBy')=='pop') selected @endif>POP</option>
                            </select>
                        </div>
                    </div>

                    <div class="row mt-2">
                        <div class="form-group col-md-3">
                            <label>Select Manager :</label>
                            <select name="reseller" id="resellers" class="form-control select2 form-control-sm">
                                <option value="">Select Manager</option>
                                <option value="all">All Manager</option>
                                @foreach ($reseller as $r)
                                    <option value="{{ $r->id }}">{{ $r->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group col-md-3">
                            <label>Select Pop/Zone :</label>
                            <select name="pop" id="pop" class="form-control select2 form-control-sm">
                                <option value="">Select Pop/Zone</option>
                                <option value="all">All Pop/Zone</option>
                                @foreach ($poplist as $pop)
                                    <option value="{{ $pop->id }}">{{ $pop->popname }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group col-md-3">
                            <label>Select Area :</label>
                            <select name="areas" id="areas" class="form-control select2 form-control-sm">
                                <option value="">Select Areas</option>
                                <option value="all">All Areas</option>
                                @foreach ($areas as $area)
                                    <option value="{{ $area->area }}">{{ $area->area }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group col-md-3">
                            <label>Username :</label>
                            <input type="text" name="username" id="username" class="form-control form-control-sm" placeholder="Username">
                        </div>
                    </div>
                </div>
            </div>

            @if (request()->type != 'all')
                @foreach ($poplist as $pop)
                    @if (request()->search == 'pop')
                        @if ($pop->id == request()->type)
                            <h2 class="text-center bold text-xl font-bold pb-2 mt-1 pop{{ $pop->id }}">
                                View Customer Billing Information Of: {{ $pop->popname }} ( {{ date('M-Y') }} )
                            </h2>
                        @endif
                    @endif
                @endforeach

                @foreach ($reseller as $r)
                    @if (request()->search == 'resellers')
                        @if ($r->id == request()->type)
                            <h2 class="text-center bold text-xl font-bold pb-2 mt-1 pop{{ $r->id }}">
                                View Customer Billing Information Of: {{ $r->name }} ( {{ date('M-Y') }} )
                            </h2>
                        @endif
                    @endif
                @endforeach

                @if (request()->search == 'area')
                    <h2 class="text-center bold text-xl font-bold pb-2 mt-1">View Customer Billing
                        Information Of: {{ request()->type }} ( {{ date('M-Y') }} )</h2>
                @endif
                <hr>
                <div class="table-responsive">
                    <table id="dataTable"
                        class="table table-bordered table-responsive pop @if (isset($pop)) {{ $pop->id }} @endif">
                        <thead class="bg-gray-50">
                            <tr>
                                <th>#</th>
                                <th>ID</th>
                                <th>Invoice</th>
                                <th class="whitespace-nowrap">User name</th>
                                <th>Name</th>
                                <th>Contact</th>
                                <th>Joining Date</th>
                                <th>Zone/POP</th>
                                <th>Package</th>
                                <th>Type</th>
                                <th>Bill Date</th>
                                <th>Expire Date</th>
                                <th>OTC</th>
                                <th>Bill Amount</th>
                                <th>Previous Due</th>
                                <th>Due Amount</th>
                                <th style="min-width: 200px;">Address</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            @php
                                $previousTotalDue = 0;
                                $total_previous_due = 0;
                                $currentTotalDue = 0;

                                $currentTotalDue2 = 0;
                                $previousTotalDue2 = 0;
                            @endphp
                            @foreach ($list as $r)
                                @php
                                    if ($r->dueAmount - $r->package_rate > 0) {
                                        $total_previous_due += $r->dueAmount - $r->package_rate;
                                    } else {
                                        $total_previous_due += 0;
                                    }
                                    $currentTotalDue += $r->dueAmount;
                                    $previous_due = $r->dueAmount - $r->billamount;
                                    $previousTotalDue += $previous_due;
                                @endphp

                                @php
                                    $current_bill = ($r->billamount - $r->paidAmount) ?? 0;
                                    $previous_due2 = ($r->dueAmount - $current_bill) ?? 0;
                                @endphp
                                <tr>
                                    <td>{{ $loop->iteration }}</td>
                                    <td>
                                        @php(printf('CID%04d', $r->id))
                                    </td>
                                    <td style="text-align: center">
                                        <a href="{{ route('invoice-pdf', $r->id) }}" target=”_blank”>
                                            <i class="fa fa-print"></i>
                                        </a>
                                    </td>
                                    <td>
                                        {{ $r->userid }}
                                    </td>
                                    <td class="whitespace-nowrap">
                                        {{ $r->clients_name ?? '' }}
                                    </td>
                                    <td>
                                        {{ $r->contact_no ?? '' }}
                                    </td>
                                    <td>
                                        {{ date('d-M-Y', strtotime($r->joinDate)) }}
                                    </td>
                                    <td>
                                        {{ $r->popname }}
                                    </td>
                                    <td>
                                        {{ $r->package_name }}
                                    </td>
                                    <td>
                                        {{ $r->billing_type }}
                                    </td>
                                    <td class="whitespace-nowrap">
                                        @if ($r->billing_type == 'new')
                                            {{ date('d-M-Y', strtotime($r->created_at)) }}
                                        @else
                                            {{ date('d-M-Y', strtotime($r->due_date)) }}
                                        @endif
                                    </td>
                                    <td>
                                        {{ date('d-M-Y', strtotime($r->expire_date)) }}
                                    </td>
                                    <td>
                                        @if ($r->otc_due == null)
                                            {{ 0 }}
                                        @else
                                            {{ $r->otc_due }}
                                        @endif
                                    </td>
                                    <td class="text-right">
                                        {{ $r->billamount }}
                                    </td>

                                    <td class="text-right">
                                        {{-- @if ($r->dueAmount - $r->package_rate > 0)
                                            {{ $r->dueAmount - $r->package_rate }}
                                        @else
                                            {{ 0 }}
                                        @endif --}}
                                       {{-- {{ number_format(abs($r->dueAmount - $r->billamount), 2) }} --}}
                                        @if ($previous_due2 < 0)
                                            {{ number_format(0, 2) }}
                                        @else
                                            @php( $previousTotalDue2 += $previous_due2)
                                            {{ number_format($previous_due2, 2) }}
                                        @endif
                                    </td>
                                    <td class="text-right">
                                        @if ($r->dueAmount < 0)
                                            {{ number_format(0, 2) }}
                                        @else
                                            @php($currentTotalDue2 += $r->dueAmount)
                                            {{ $r->dueAmount }}
                                        @endif
                                    </td>
                                    <td>
                                        @cannot('area_hide_bill_sheet')
                                            @if (!empty($r->area))
                                                <b>Area :</b> {{ $r->area ?? '' }}.
                                            @endif
                                        @endcannot
                                        @if (!empty($r->block_sector))
                                            <b>Block/Sector :</b> {{ $r->block_sector ?? '' }}.
                                        @endif
                                        @if (!empty($r->road_name))
                                            <b>R Name :</b> {{ $r->road_name ?? '' }}.
                                        @endif
                                        @if (!empty($r->road_no))
                                            <b>R No :</b> {{ $r->road_no ?? '' }}.
                                        @endif
                                        @if (!empty($r->building_name))
                                            <b>B Name :</b> {{ $r->building_name ?? '' }}.
                                        @endif
                                        @if (!empty($r->building_no))
                                            <b>B No :</b> {{ $r->building_no ?? '' }}.
                                        @endif
                                        @if (!empty($r->flat_no))
                                            <b>F No :</b> {{ $r->flat_no ?? '' }}.
                                        @endif
                                        @if (!empty($r->owner_name))
                                            <b>H O :</b> {{ $r->owner_name ?? '' }}.
                                        @endif
                                        @if (!empty($r->box))
                                            <b>Box :</b> {{ $r->box ?? '' }}
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                            <tr>
                                <td colspan="13"></td>
                                <td class="text-right">BDT {{ $list->sum('billamount') }}</td>
                                {{-- <td class="text-right">BDT {{ $total_previous_due }}</td> --}}
                                <td class="text-right">BDT {{ $previousTotalDue2 }}</td>
                                <td class="text-right">BDT {{ $currentTotalDue2 ?? '' }}</td>
                                <td></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            @else
                @foreach ($poplist as $pop)
                    <h2 class="text-center bold text-xl font-bold pb-5 mt-5 pop{{ $pop->id }}">View Customer Billing
                        Information Of: {{ $pop->popname }} ( {{ date('M-Y') }} )</h2>
                    <hr>
                    <table id="dataTable" class="table table-bordered pop{{ $pop->id }}">
                        <thead class="bg-gray-50 table-header-group">
                            <tr>
                                <th>#</th>
                                <th>ID</th>
                                <th>Invoice</th>
                                <th class="whitespace-nowrap">User name</th>
                                <th>Name</th>
                                <th>Contact</th>
                                <th>Zone/POP</th>
                                <th>Package</th>
                                <th>Type</th>
                                <th>Bill Date</th>
                                <th>Previous Due</th>
                                <th>Due Amount</th>
                                <th style="min-width: 200px;">Address</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            @php($currentDue = 0)
                            @foreach ($list as $r)
                                @if ($r->pop_id == $pop->id)
                                    @php($currentDue += $r->dueAmount)
                                    <tr>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>
                                            @php(printf('CID%04d', $r->id))
                                        </td>
                                        <td></td>
                                        <td>
                                            {{ $r->userid }}
                                        </td>
                                        <td class="whitespace-nowrap">
                                            {{ $r->clients_name ?? '' }}
                                        </td>
                                        <td>
                                            {{ $r->contact_no ?? '' }}
                                        </td>
                                        <td>
                                            {{ $r->popname }}
                                        </td>
                                        <td>
                                            {{ $r->package_name }}
                                        </td>
                                        <td>
                                            {{ $r->billing_type }}
                                        </td>
                                        <td class="whitespace-nowrap">
                                            @if ($r->billing_type == 'new')
                                                {{ date('d-M-Y', strtotime($r->created_at)) }}
                                            @else
                                                {{ date('d-M-Y', strtotime($r->due_date)) }}
                                            @endif
                                        </td>
                                        <td>
                                            @if ($r->dueAmount - $r->package_rate > 0)
                                                {{ $r->dueAmount - $r->package_rate }}
                                            @else
                                                {{ 0 }}
                                            @endif
                                        </td>
                                        <td class="text-right">
                                            @if ($r->dueAmount < 0)
                                                {{ number_format(0, 2) }}
                                            @else
                                                {{ $r->dueAmount }}
                                            @endif
                                        </td>
                                        <td>
                                            @if (!empty($r->area))
                                                <b>Area :</b> {{ $r->area ?? '' }}.
                                            @endif
                                            @if (!empty($r->block_sector))
                                                <b>Block/Sector :</b> {{ $r->block_sector ?? '' }}.
                                            @endif
                                            @if (!empty($r->road_name))
                                                <b>R Name :</b> {{ $r->road_name ?? '' }}.
                                            @endif
                                            @if (!empty($r->road_no))
                                                <b>R No :</b> {{ $r->road_no ?? '' }}.
                                            @endif
                                            @if (!empty($r->building_name))
                                                <b>B Name :</b> {{ $r->building_name ?? '' }}.
                                            @endif
                                            @if (!empty($r->building_no))
                                                <b>B No :</b> {{ $r->building_no ?? '' }}.
                                            @endif
                                            @if (!empty($r->flat_no))
                                                <b>F No :</b> {{ $r->flat_no ?? '' }}.
                                            @endif
                                            @if (!empty($r->owner_name))
                                                <b>H O :</b> {{ $r->owner_name ?? '' }}.
                                            @endif
                                            @if (!empty($r->box))
                                                <b>Box :</b> {{ $r->box ?? '' }}
                                            @endif
                                        </td>
                                    </tr>
                                @endif
                            @endforeach
                            <tr>
                                <td colspan="11" class="text-right">Total Due Amount</td>
                                <td class="text-right">BDT {{ $currentDue }}</td>
                            </tr>
                        </tbody>
                    </table>
                @endforeach
            @endif
        </div>
    </div>


    <style>
        .pop {
            display: none;
        }



        @media print {


            table tr th,
            table,
            tr,
            td {
                font-size: 10px !important;
                padding: 2px !important;
            }
        }
    </style>

@endsection

@section('ajax')
    <script>
        function export2csv() {
            let data = "";
            const tableData = [];
            const rows = document.querySelectorAll("table#dataTable 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");

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


    <script type="text/javascript">
        $(document).ready(function() {
            $('#sortBy').on('change', function() {
                var params = new URLSearchParams(window.location.search);
                var sortBy = $('#sortBy').val();
                if (sortBy) {
                    params.set('sortBy', sortBy);
                } else {
                    params.delete('sortBy');
                }
                window.location.href = "{{ route('billSheet') }}" + "?" + params.toString();
            });

            $('#pop').on('change', function() {
                var type = $("#pop").val();
                var sortBy = $('#sortBy').val() || "{{ request()->get('sortBy') }}";
                window.location.href = "{{ route('billSheet') }}" + "?type=" + type + "&search=pop" + (sortBy ? "&sortBy=" + sortBy : "");
            });

            $('#username').on('change', function() {
                var type = $("#username").val();
                var sortBy = $('#sortBy').val() || "{{ request()->get('sortBy') }}";
                window.location.href = "{{ route('billSheet') }}" + "?type=" + type + "&search=username" + (sortBy ? "&sortBy=" + sortBy : "");
            });

            $('#areas').on('change', function() {
                var type = $("#areas").val();
                var sortBy = $('#sortBy').val() || "{{ request()->get('sortBy') }}";
                window.location.href = "{{ route('billSheet') }}" + "?type=" + type + "&search=area" + (sortBy ? "&sortBy=" + sortBy : "");
            });

            $('#resellers').on('change', function() {
                var type = $("#resellers").val();
                var sortBy = $('#sortBy').val() || "{{ request()->get('sortBy') }}";
                window.location.href = "{{ route('billSheet') }}" + "?type=" + type +
                    "&search=resellers" + (sortBy ? "&sortBy=" + sortBy : "");
            });

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


        });
    </script>
@endsection
