@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 d-flex flex-wrap gap-2">
                    <button type="button" class="btn" onclick="export2csv()" style="background: #a21caf;color:#FFFFFF;">Download csv</button>
                    <button type="button" class="btn ml-1" onclick="printTable()" style="background: #28a745;color:#FFFFFF;">🖨️ Print</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">
                <h2 id="printTitle" style="display: none; text-align: center; margin-bottom: 15px;">Due Customer List</h2>
                <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_column">Status</th>
                            <th class="status_column">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");

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

        function printTable() {
            const table = document.getElementById('result_table');

            if (!table || table.rows.length <= 1) {
                alert('No data to print. Please search for due customers first.');
                return;
            }

            // Add print styles to the page
            const printStyle = document.createElement('style');
            printStyle.id = 'print-styles';
            printStyle.innerHTML = `
                @media print {
                    @page {
                        margin: 0.5cm;
                        size: A4 landscape;
                    }

                    /* Force all text to very dark black with print color adjustment */
                    * {
                        color: #000000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }

                    /* Hide navigation, headers, forms, and buttons */
                    nav, header, footer, .navbar, .sidebar,
                    .card:first-child, #search, .form-group,
                    .btn, #downloadFile {
                        display: none !important;
                    }

                    /* Show the wrapper container with totals at top */
                    .w-100.d-flex.justify-content-between {
                        display: flex !important;
                        flex-direction: column !important;
                        width: 100% !important;
                        margin-bottom: 15px !important;
                    }

                    /* Show the result container */
                    #result {
                        display: block !important;
                        width: 100% !important;
                        margin: 0 !important;
                        padding: 0 !important;
                        color: #000000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }

                    /* Ensure table is visible */
                    .table-responsive {
                        display: block !important;
                        overflow: visible !important;
                        width: 100% !important;
                    }

                    #result_table {
                        display: table !important;
                        width: 100% !important;
                        border-collapse: collapse !important;
                        margin: 0 auto !important;
                        font-size: 9px !important;
                        color: #000000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }

                    #result_table thead {
                        display: table-header-group !important;
                    }

                    #result_table tbody {
                        display: table-row-group !important;
                    }

                    #result_table tr {
                        display: table-row !important;
                        page-break-inside: avoid !important;
                        color: #000000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }

                    #result_table th,
                    #result_table td {
                        display: table-cell !important;
                        border: 1px solid #000 !important;
                        padding: 4px !important;
                        font-size: 9px !important;
                        color: #000000 !important;
                        background-color: #FFFFFF !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                        font-weight: 500 !important;
                    }

                    #result_table th {
                        background-color: #FFFFFF !important;
                        color: #000000 !important;
                        font-weight: bold !important;
                        border: 2px solid #000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }

                    /* Remove background colors from status cells */
                    #result_table td.bg-success,
                    #result_table td.bg-danger,
                    #result_table td.bg-warning,
                    #result_table td.bg-secondary,
                    #result_table td.bg-dark {
                        background-color: #FFFFFF !important;
                        color: #000000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                        font-weight: 500 !important;
                    }

                    /* Make all text content darker */
                    #result_table td,
                    #result_table th,
                    #result_table a,
                    #result_table b,
                    #result_table strong {
                        color: #000000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                        font-size: 9px !important;
                    }

                    /* Show total container at the top */
                    #totalContainer {
                        display: flex !important;
                        flex-direction: row !important;
                        justify-content: center !important;
                        align-items: center !important;
                        margin-top: 0 !important;
                        margin-bottom: 20px !important;
                        text-align: center !important;
                        page-break-inside: avoid !important;
                        color: #000000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                        font-weight: bold !important;
                        position: relative !important;
                        width: 100% !important;
                        padding: 15px 0 !important;
                        border-bottom: 2px solid #000 !important;
                    }

                    #totalContainer * {
                        color: #000000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                        font-weight: bold !important;
                        font-size: 9px !important;
                    }

                    #totalContainer p {
                        display: inline-block !important;
                        margin: 0 20px !important;
                        padding: 8px 15px !important;
                        font-size: 14px !important;
                        border: 1px solid #000 !important;
                        border-radius: 4px !important;
                    }

                    #totalContainer .border {
                        border: 1px solid #000 !important;
                    }

                    #totalContainer span {
                        font-size: 9px !important;
                    }

                    /* Hide card wrapper but show content */
                    .card {
                        border: none !important;
                        box-shadow: none !important;
                    }

                    .card-body {
                        padding: 0 !important;
                    }

                    /* Ensure all links and buttons are black */
                    a, button, .btn {
                        color: #000000 !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }

                    /* Keep CID link visible (it uses btn classes) */
                    #result_table a.btn {
                        display: inline-block !important;
                        background: transparent !important;
                        border: 1px solid #000 !important;
                        color: #000 !important;
                        padding: 2px 6px !important;
                        font-size: 9px !important;
                        text-decoration: none !important;
                    }

                    /* Hide Change button and other action buttons in print */
                    .changeExpireDate,
                    button.changeExpireDate,
                    .dropdown-item.changeExpireDate,
                    .badge.changeExpireDate,
                    button[data-toggle="modal"],
                    .btn[data-target="#changeExpireDate"] {
                        display: none !important;
                        visibility: hidden !important;
                    }
                }
            `;

            // Remove existing print styles if any
            const existingStyle = document.getElementById('print-styles');
            if (existingStyle) {
                existingStyle.remove();
            }

            // Add print styles to head
            document.head.appendChild(printStyle);

            // Trigger print dialog
            window.print();
        }
    </script>
@endsection

