<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('header', null, []); ?> 
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <h2 class="h4 mb-0"><?php echo e($pageTitle ?? 'Bill Generate'); ?></h2>
            </div>
            <div class="d-flex gap-2">
                <button class="btn btn-outline-primary d-lg-none" type="button" data-bs-toggle="collapse" data-bs-target="#billingFilters"><i data-feather="filter"></i> Filters</button>
                <button id="headerPrintSelectedButton" class="btn btn-primary d-none d-sm-inline-flex"><i data-feather="printer"></i> Print Selected</button>
            </div>
        </div>
     <?php $__env->endSlot(); ?>
    <style>
        .table-responsive {
            overflow-x: auto;
        }

        .calendar-only-wrap {
            width: 32px;
        }

        .calendar-only {
            width: 32px;
            height: 32px;
            padding: 0;
            border: none;
            background: transparent;
            cursor: pointer;
            color: transparent;
        }

        .calendar-only::-webkit-datetime-edit {
            display: none;
        }

        .calendar-only::-webkit-calendar-picker-indicator {
            font-size: 18px;
            cursor: pointer;
            opacity: 1;
        }

        /* Theme color overrides for Billing cards to make look distinct */
        .bg-gradient-end-1 { background: linear-gradient(90deg,#0ea5a4,#06b6d4) !important; color: #fff !important; }
        .bg-gradient-end-3 { background: linear-gradient(90deg,#f59e0b,#f97316) !important; color: #fff !important; }
        .bg-gradient-start-5 { background: linear-gradient(90deg,#ef4444,#dc2626) !important; color: #fff !important; }

        /* Responsive table tweaks */
        .table td, .table th { vertical-align: middle; }
        .table .btn { margin-right: 6px; margin-bottom: 6px; }

        @media (max-width: 768px) {
            .table { font-size: 13px; }
            .table td .btn { display: inline-block; padding: 6px 8px; }
            .disc-day { font-size: 11px; }
            .table-responsive { overflow-x: auto; }
        }
        .billing-filter-card .card-header { background: #f8fafc; }
        .billing-summary-card { min-height: 116px; }
        .billing-summary-shell { background: transparent; border: 0 !important; box-shadow: none !important; }
        .billing-summary-shell > .card-body { padding: 0; }
        .billing-summary-card h6 { color: #fff; font-size: 1.45rem; margin: 4px 0 0; }
        .billing-summary-card .text-secondary-light, .billing-summary-card .text-danger { color: rgba(255,255,255,.85) !important; }
        .billing-table-card .card-body { min-width: 0; }
        .billing-table-scroll { width: 100%; max-width: 100%; min-width: 0; overflow-x: auto; overscroll-behavior-inline: contain; }
        .billing-table-scroll .dataTables_wrapper { width: 100%; min-width: 0; }
        #customer-datatable { width: 100% !important; }
        #customer-datatable .billing-select-column { width: 44px !important; min-width: 44px; text-align: center; padding-left: .5rem; padding-right: .5rem; }
        #customer-datatable .billing-select-column::before,
        #customer-datatable .billing-select-column::after { display: none !important; content: none !important; }
        .billing-check-wrap { min-height: 22px; display: inline-flex; align-items: center; justify-content: center; margin: 0; padding: 0; }
        .billing-check-wrap .form-check-input { float: none; width: 18px; height: 18px; margin: 0; cursor: pointer; }
        .billing-actions { display: flex; flex-wrap: wrap; gap: 5px; min-width: 160px; }
        .billing-actions .btn { margin: 0; }
        @media (min-width: 992px) { #billingFilters.collapse { display: block !important; } }
        @media (max-width: 1399.98px) {
            .bill-generate-page .card-body { padding: 16px; }
            #customer-datatable { font-size: 12px; }
            #customer-datatable th, #customer-datatable td { padding: .6rem .5rem; }
            .billing-actions { min-width: 145px; }
        }
        @media (max-width: 575.98px) {
            .billing-summary-card { min-height: 98px; }
            #paymentModal .modal-body { margin: 0 !important; }
            #paymentModal #submit-btn { width: 100%; min-height: 48px; }
        }
    </style>

    <div class="row gy-4 bill-generate-page">
        <div class="col-12">
            <div class="billing-mode-switch d-flex flex-wrap gap-2">
                <a href="<?php echo e(route('admin.billings.generate')); ?>" class="btn <?php echo e(($pageMode ?? 'generate') === 'generate' ? 'btn-primary' : 'btn-outline-primary'); ?>"><i data-feather="file-plus"></i> Bill Generate & Due</a>
                <a href="<?php echo e(route('admin.billings.full_paid')); ?>" class="btn <?php echo e(($pageMode ?? '') === 'full_paid' ? 'btn-success' : 'btn-outline-success'); ?>"><i data-feather="check-circle"></i> Full Paid</a>
            </div>
        </div>
        <div class="col-md-12">
            <div class="card billing-filter-card">
                <div class="card-header d-flex align-items-center justify-content-between">
                    
                    <button class="btn btn-sm btn-outline-secondary d-lg-none" type="button" data-bs-toggle="collapse" data-bs-target="#billingFilters">Show / Hide</button>
                </div>
                <div class="card-body collapse" id="billingFilters">
                    <div class="form-wizard">
                        <fieldset class="wizard-fieldset show">
                            <div class="row gy-3">
                                <div class="col-12 col-sm-6 col-lg-3">
                                    <label for="zone-filter" class="form-label">Zone</label>
                                    <div>
                                        <select id="zone-filter" class="form-control">
                                            <option value="">All Zones</option>
                                            <?php $__currentLoopData = $bzones; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $zone): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <option value="<?php echo e($zone->zone); ?>"><?php echo e($zone->zone); ?></option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-12 col-sm-6 col-lg-3">
                                    <label for="billing-person-filter" class="form-label">Billing Person</label>
                                    <div class="position-relative">
                                        <select id="billing-person-filter" class="form-control">
                                            <option value="">All Billing Persons</option>
                                            <?php $__currentLoopData = $bbillingperson; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $bp): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <option value="<?php echo e($bp->id); ?>"><?php echo e($bp->name); ?></option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-12 col-sm-6 col-lg-2">
                                    <label for="status-filter" class="form-label">Status</label>
                                    <div class="position-relative">
                                        <select id="status-filter" class="form-control">
                                            <option value="">All Due</option>
                                            <option value="0">UnPaid</option>
                                            <option value="1">Partial</option>
                                            <option value="2">Paid</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-12 col-sm-6 col-lg-2">
                                    <label for="disconnect-date-from" class="form-label">Disconnect From Date</label>
                                    <div class="position-relative">
                                        <input type="date" id="disconnect-date-from" class="form-control">
                                    </div>
                                </div>
                                <div class="col-12 col-sm-6 col-lg-2">
                                    <label for="disconnect-date-to" class="form-label">Disconnect To Date</label>
                                    <div class="position-relative">
                                        <input type="date" id="disconnect-date-to" class="form-control">
                                    </div>
                                </div>
                                <div class="col-12 d-flex flex-wrap justify-content-end gap-2 pt-2">
                                    <button type="button" id="resetBillingFilters" class="btn btn-outline-secondary"><i data-feather="rotate-ccw"></i> Reset</button>
                                    <button type="button" id="applyBillingFilters" class="btn btn-primary"><i data-feather="search"></i> Search Bills</button>
                                </div>
                            </div>
                        </fieldset>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-12">
            <div class="card billing-summary-shell h-100 p-0 radius-12">
                <div class="card-body p-24">
                    <div class="mt-24">
                        <div class="row mt-24 gy-3">
                            <div class="col-xxl-3 col-sm-6">
                                <div class="card billing-summary-card p-3 shadow-none radius-8 border h-100 bg-gradient-end-1">
                                    <div class="card-body p-0">
                                        <div class="d-flex flex-wrap align-items-center justify-content-between gap-1 mb-8">
                                            <div class="d-flex align-items-center gap-2">
                                                <span class="mb-0 w-48-px h-48-px bg-primary-600 flex-shrink-0 text-white d-flex justify-content-center align-items-center rounded-circle h6 mb-0">
                                                    <iconify-icon icon="hugeicons:invoice-03" class="icon"></iconify-icon>
                                                </span>
                                                <div>
                                                    <span class="mb-2 fw-medium text-secondary-light text-sm">Total Due</span>
                                                    <h6 class="fw-semibold" id="totalDue">0</h6>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xxl-3 col-sm-6">
                                <div class="card billing-summary-card p-3 shadow-none radius-8 border h-100 bg-gradient-end-3">
                                    <div class="card-body p-0">
                                        <div class="d-flex flex-wrap align-items-center justify-content-between gap-1 mb-8">
                                            <div class="d-flex align-items-center gap-2">
                                                <span class="mb-0 w-48-px h-48-px bg-warning-600 flex-shrink-0 text-white d-flex justify-content-center align-items-center rounded-circle h6 mb-0">
                                                    <iconify-icon icon="hugeicons:invoice-03" class="icon"></iconify-icon>
                                                </span>
                                                <div>
                                                    <span class="mb-2 fw-medium text-secondary-light text-sm"><span class="text-danger"><?php echo e(date('F')); ?></span> Month Due</span>
                                                    <h6 class="fw-semibold" id="runningMonthDue">0</h6>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xxl-3 col-sm-6">
                                <div class="card billing-summary-card p-3 shadow-none radius-8 border h-100 bg-gradient-end-1">
                                    <div class="card-body p-0">
                                        <div class="d-flex flex-wrap align-items-center justify-content-between gap-1 mb-8">
                                            <div class="d-flex align-items-center gap-2">
                                                <span class="mb-0 w-48-px h-48-px bg-primary-600 flex-shrink-0 text-white d-flex justify-content-center align-items-center rounded-circle h6 mb-0">
                                                    <iconify-icon icon="hugeicons:invoice-03" class="icon"></iconify-icon>
                                                </span>
                                                <div>
                                                    <span class="mb-2 fw-medium text-secondary-light text-sm">Total Previous Due</span>
                                                    <h6 class="fw-semibold" id="totalPreviousDue">0</h6>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xxl-3 col-sm-6">
                                <div class="card billing-summary-card p-3 shadow-none radius-8 border h-100 bg-gradient-start-5">
                                    <div class="card-body p-0">
                                        <div class="d-flex flex-wrap align-items-center justify-content-between gap-1 mb-8">
                                            <div class="d-flex align-items-center gap-2">
                                                <span class="mb-0 w-48-px h-48-px border-danger-light-white bg-danger flex-shrink-0 text-white d-flex justify-content-center align-items-center rounded-circle h6 mb-0">
                                                    <iconify-icon icon="flowbite:users-group-solid" class="icon"></iconify-icon>
                                                </span>
                                                <div>
                                                    <span class="mb-2 fw-medium text-secondary-light text-sm"><span class="text-danger"><?php echo e(date('F')); ?></span> Due Customers</span>
                                                    <h6 class="fw-semibold" id="totalDueCustomers">0</h6>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-12">
            <div class="card basic-data-table billing-table-card">
                <div class="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
                    <div>
                        <h5 class="card-title mb-0"><?php echo e($pageTitle ?? 'Bill Collection List'); ?></h5>
                  
                    </div>
                    <div class="d-flex gap-2">
                        <button id="printSelectedButton" class="btn btn-primary btn-sm"><i data-feather="printer"></i> Print Selected</button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="billing-table-scroll">
                    <table class="table table-striped bordered-table mb-0" id="customer-datatable" data-page-length="10">
                        <thead>
                            <tr>
                                <th scope="col" class="billing-select-column" data-dt-order="disable" aria-label="Select all bills">
                                    <div class="billing-check-wrap">
                                        <input class="form-check-input" type="checkbox" id="check-all" aria-label="Select all bills on this page">
                                    </div>
                                </th>
                                <th scope="col" data-dt-order="disable">Action</th>
                                <th scope="col">ID</th>
                                <th scope="col">Name</th>
                                <th scope="col">PPPoE Username</th>
                                <th scope="col">Address</th>
                                <th scope="col">Mobile No</th>
                                <th scope="col">Package</th>
                                <th scope="col">Monthly Bill</th>
                                <th scope="col">Total Due</th>
                                <th scope="col">Previous Due</th>
                                <th scope="col">Disconn. Date</th>
                                <th scope="col">Grace</th>
                                <th scope="col">Zone</th>
                                <th scope="col">B.Person</th>
                                <th scope="col">Status</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                        <tfoot>
                            <tr>
                                <th colspan="8" class="text-end">Page Total:</th>
                                <th id="ft_monthly"></th>
                                <th id="ft_total_due"></th>
                                <th id="ft_prev_due"></th>
                                <th colspan="5"></th>
                            </tr>
                        </tfoot>
                    </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <div><h5 class="modal-title fs-5" id="paymentModalLabel">Collect New Payment</h5><small class="text-muted" id="paymentCustomerName">Customer</small></div>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body m-3">
                        <form id="paymentForm">
                            <input type="hidden" id="customer_id" name="customer_id" class="form-control">
                            <input type="hidden" id="billing_id" name="billing_id" class="form-control">
                            <div class="form-group mb-2">
                                <label for="payment_month" class="form-label fw-semibold">Payment month</label>
                                <input type="month" id="payment_month" name="payment_month" class="form-control" required>
                            </div>
                            <div class="form-group mt-3 mb-1">
                                <div class="alert alert-warning py-2 mb-2">Current due: <strong><span id="due-amount">0</span></strong></div>
                                <label for="amount" class="form-label fw-semibold">Amount received</label>
                                <input type="number" min="0" step="0.01" inputmode="decimal" id="amount" name="amount" class="form-control form-control-lg" value="0" required>
                                <div class="d-flex gap-2 mt-2"><button type="button" class="btn btn-sm btn-outline-success" id="payFullDue">Full Due</button><button type="button" class="btn btn-sm btn-outline-secondary" id="clearPayAmount">Clear</button></div>
                            </div>
                            <div class="form-group mb-1">
                                <label for="discount" class="form-label fw-semibold">Discount <small class="text-muted">Keep 0 if not applicable</small></label>
                                <input type="number" min="0" step="0.01" inputmode="decimal" id="discount" name="discount" class="form-control" value="0">
                            </div>
                            <div class="form-group mb-1">
                                <label for="payment_type" class="form-label fw-semibold">Payment method</label>
                                <select id="payment_type" name="payment_type" class="form-control">
                                    <option value="1" selected>Cash</option>
                                    <option value="2">Bkash</option>
                                    <option value="3">Nagad</option>
                                    <option value="4">Bank</option>
                                </select>
                            </div>
                            <div class="form-group mb-3">
                                <label for="discription">Note <small class="text-muted">(optional)</small></label>
                                <textarea id="discription" name="discription" class="form-control" maxlength="500" placeholder="Example: August 2026 bill payment"></textarea>
                            </div>
                            <div class="form-group mb-3">
                                <div class="form-check form-switch app-toggle switch-success">
                                    <input class="form-check-input" type="checkbox" role="switch" id="smssend" name="smssend" value="smssend" checked>
                                    <label class="form-check-label line-height-1 fw-medium text-secondary-light" for="smssend">Send SMS to customer</label>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary" id="submit-btn">
                                <span class="btn-label">Save Payment</span>
                                <span class="btn-loader d-none"><i class="fa fa-spinner fa-spin"></i> Processing...</span>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="graceExtensionModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <div><h5 class="modal-title">Temporary Grace / Extend Line</h5><small class="text-muted" id="graceCustomerName">Customer</small></div>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body m-3">
                        <form id="graceExtensionForm">
                            <input type="hidden" id="grace_customer_id">
                            <div class="alert alert-light border mb-3">Original disconnect date: <strong id="graceCurrentDate">Not set</strong></div>
                            <div class="alert alert-warning py-2 mb-3">Active grace until: <strong id="graceExistingUntil">No active grace</strong></div>
                            <div class="form-group mb-3">
                                <label for="grace_days" class="form-label fw-semibold">Extend by days</label>
                                <input type="number" min="1" max="30" id="grace_days" class="form-control" value="2" required>
                            </div>
                            <div class="form-group mb-3">
                                <label for="grace_reason" class="form-label fw-semibold">Reason</label>
                                <textarea id="grace_reason" class="form-control" maxlength="255" rows="3" placeholder="Example: Customer requested 2 extra days"></textarea>
                            </div>
                            <div class="form-group mb-3">
                                <div class="form-check form-switch app-toggle switch-success">
                                    <input class="form-check-input" type="checkbox" role="switch" id="grace_send_sms" checked>
                                    <label class="form-check-label line-height-1 fw-medium text-secondary-light" for="grace_send_sms">Send SMS to customer</label>
                                </div>
                            </div>
                            <button type="button" class="btn btn-warning" id="saveGraceBtn">
                                <span class="btn-label">Save Grace</span>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

       
    </div>

    <?php $__env->startPush('scripts'); ?>
        <script>
            $(document).ready(function() {
                var pageMode = '<?php echo e($pageMode ?? 'generate'); ?>';
                var canTakePayment = <?php echo json_encode(auth()->user()->can('billing.update'), 15, 512) ?>;
                var defaultStatusFilter = '<?php echo e($defaultStatusFilter ?? ''); ?>';
                var paymentDescriptionTouched = false;
                if (defaultStatusFilter !== '') {
                    $('#status-filter').val(defaultStatusFilter);
                }

                function buildPaymentDescription(monthValue) {
                    if (!monthValue) return '';
                    var parts = monthValue.split('-');
                    if (parts.length !== 2) return '';
                    var year = parseInt(parts[0], 10);
                    var monthIndex = parseInt(parts[1], 10) - 1;
                    var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                    if (Number.isNaN(year) || !monthNames[monthIndex]) return '';
                    return monthNames[monthIndex] + ' ' + year + ' bill payment';
                }

                function updatePaymentDescription(force) {
                    var description = buildPaymentDescription($('#payment_month').val());
                    if (!description) {
                        if (force) {
                            $('#discription').val('');
                        }
                        return;
                    }
                    if (force || !paymentDescriptionTouched || !$('#discription').val().trim()) {
                        $('#discription').val(description);
                    }
                }

                $('#payment_month').on('change input', function() {
                    updatePaymentDescription(false);
                });

                $('#discription').on('input', function() {
                    paymentDescriptionTouched = $(this).val().trim().length > 0;
                });
                var table = $('#customer-datatable').DataTable({
                    dom: `<"row"<"col-sm-6"l><"col-sm-6 text-end"f>>` +
                        `<"row"<"col-sm-12 text-end"B>>` +
                        `<"row dt-layout-row"<"col-sm-12"tr>>` +
                        `<"row"<"col-sm-5"i><"col-sm-7 text-end"p>>`,
                    keys: true,
                    stateSave: true,
                    stateLoadParams: function(settings, data) {
                        if (!data.order || !data.order.length || Number(data.order[0][0]) < 2) {
                            data.order = [[2, 'asc']];
                        }
                        if (data.search) {
                            data.search.search = '';
                        }
                    },
                    lengthChange: true,
                    responsive: {
                        details: { type: 'inline', target: 'tr' }
                    },
                    autoWidth: false,
                    scrollCollapse: true,
                    pagingType: "full_numbers",
                    pageLength: 10,
                    processing: true,
                    serverSide: true,
                    columnDefs: [
                        { targets: 0, orderable: false, searchable: false, className: 'billing-select-column', width: '44px', responsivePriority: 1 },
                        { targets: 1, orderable: false, searchable: false, responsivePriority: 2 }, // Actions
                        { responsivePriority: 2, targets: 3 }, // Name
                        { responsivePriority: 3, targets: 2 }, // ID
                        { responsivePriority: 4, targets: 9 }, // Total Due
                        { responsivePriority: 5, targets: 11 }, // Disconnect
                        { responsivePriority: 6, targets: 12 }, // Grace
                        { responsivePriority: 7, targets: 8 } // Monthly Bill
                    ],
                    order: [[2, 'asc']],
                    ajax: {
                        url: '<?php echo e(route('admin.billings.data')); ?>',
                        type: 'GET',
                        data: function(d) {
                            d.zone = $('#zone-filter').val();
                            d.sub_zone = $('#sub-zone-filter').val();
                            d.bid = $('#billing-person-filter').val();
                            d.status = $('#status-filter').val();
                            d.page_mode = pageMode;
                            d.disconnectdatefrom = $('#disconnect-date-from').val();
                            d.disconnectdateto = $('#disconnect-date-to').val();
                        }
                    },
                    columns: [
                        {
                            data: 'ag_id',
                            orderable: false,
                            searchable: false,
                            render: function(data, type, row) {
                                return `<span class="billing-check-wrap"><input type="checkbox" class="form-check-input row-check" value="${row.id}" aria-label="Select bill"></span>`;
                            }
                        },
                        {
                            data: 'ag_id',
                            orderable: false,
                            searchable: false,
                            render: function(data, type, row) {
                                var printButton = `<a href="<?php echo e(route('admin.billings.print')); ?>?ids[]=${row.id}" target="_blank" class="btn btn-outline-secondary btn-sm" title="Print receipt"><i data-feather="printer"></i><span>Print</span></a>`;
                                if (pageMode === 'full_paid') {
                                    return `<div class="billing-actions">${printButton}</div>`;
                                }
                                var payButton = canTakePayment
                                    ? `<button class='btn btn-success btn-sm' data-name='${row.ag_name}' data-billing-id='${row.id}' data-customer-id='${row.customer_id}' data-due='${row.dueadvance}' onclick='openPaymentModal(this)'><i data-feather="credit-card"></i> Pay</button>`
                                    : '';
                                var graceButton = canTakePayment
                                    ? `<button class='btn btn-outline-warning btn-sm' data-name='${row.ag_name}' data-code='${row.cus_id}' data-customer-id='${row.customer_id}' data-disconnect='${row.mikrotik_disconnect}' data-grace-until='${row.grace_until || ''}' onclick='openGraceModal(this)'><i data-feather="clock"></i> Grace</button>`
                                    : '';
                                return `<div class="billing-actions">${payButton}${graceButton}${printButton}</div>`;
                            }
                        },
                        {
                            data: 'cus_id',
                            orderable: true,
                            render: function(data, type, row) {
                                return `<a class="btn btn-outline-success waves-effect waves-light btn-sm" title="Customer Ledger" href="<?php echo e(url('admin/customers/')); ?>/${row.customer_id}/ledger"> ${data} </a>`
                            }
                        },
                        { data: 'ag_name', orderable: true, render: function(data) { return `<span class='text-wrap'>${data}</span>`; } },
                        { data: 'ip', orderable: true },
                        { data: 'ag_office_address', orderable: true, render: function(data) { return data ? `<span class='text-wrap'>${data}</span>` : 'N/A'; } },
                        { data: 'ag_mobile_no', orderable: true, defaultContent: 'N/A' },
                        { data: 'mb', orderable: true },
                        { data: 'taka', orderable: true },
                        { data: 'dueadvance', orderable: true },
                        {
                            data: 'dueadvance',
                            orderable: true,
                            render: function(data, type, row) {
                                if (row.status === 'paid') {
                                    return '0.00';
                                }
                                var totalDue = parseFloat(data) || 0;
                                var monthlyBillAmount = parseFloat(row.mb) || 0;
                                var dueValue = totalDue > monthlyBillAmount ? totalDue - monthlyBillAmount : 0;
                                return dueValue.toFixed(2);
                            }
                        },
                        {
                            data: 'mikrotik_disconnect',
                            orderable: true,
                            render: function(data, type, row) {
                                var currentDate = data && data !== '0000-00-00' ? data.split(' ')[0] : 'N/A';
                                return `<div style="min-width:180px"><div class="disc-day" style="font-size:12px;margin-bottom:4px;">Day: <b>${currentDate}</b></div>` +
                                    `<div class="calendar-only-wrap"><input type="date" class="disconnect-date calendar-only" data-customer-id='${row.customer_id}' value="${currentDate !== 'N/A' ? currentDate : ''}" /></div></div>`;
                            }
                        },
                        {
                            data: 'grace_info',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                if (!data || !data.until) {
                                    return `<span class="text-muted small">No grace</span>`;
                                }
                                var reason = data.reason ? `<div class="small text-muted text-wrap">${data.reason}</div>` : '';
                                return `<div style="min-width:140px"><span class="badge bg-warning text-dark">${data.days_left} day(s)</span><div class="small fw-semibold mt-1">${data.until}</div>${reason}</div>`;
                            }
                        },
                        { data: 'zone', orderable: true },
                        { data: 'billing_person', orderable: true },
                        {
                            data: 'status',
                            orderable: true,
                            render: function(data) {
                                var status = String(data || 'pending').toLowerCase();
                                var color = status === 'paid' ? 'success' : (status === 'partial' ? 'warning' : 'danger');
                                return `<span class="badge bg-${color}">${status.charAt(0).toUpperCase() + status.slice(1)}</span>`;
                            }
                        }
                    ],
                    language: {
                        search: '',
                        searchPlaceholder: 'Search by ID, name, mobile or IP',
                        lengthMenu: '_MENU_ rows',
                        emptyTable: 'No billing records found',
                        zeroRecords: 'No records matched your search/filter'
                    },
                    drawCallback: function(settings) {
                        var api = this.api();
                        var sum = function(index) {
                            return api.column(index, { page: 'current' }).data().reduce(function(a, b) {
                                return parseFloat(a) + parseFloat(b || 0);
                            }, 0);
                        };
                        $('#ft_monthly').html(sum(8));
                        $('#ft_total_due').html(sum(9));
                        $('#ft_prev_due').html(sum(10));

                        // Replace feather icons for dynamically added buttons
                        try {
                            if (window.feather) window.feather.replace();
                        } catch (e) { console.warn('feather replace failed', e); }
                    }
                });
 
                table.on('xhr.dt', function(e, settings, json) {
                if (json && json.summary) {
                    $('#totalDue').text(parseFloat(json.summary.totalDue || 0).toFixed(2));
                    $('#runningMonthDue').text(parseFloat(json.summary.runningMonthDue || 0).toFixed(2));
                    $('#totalPreviousDue').text(parseFloat(json.summary.previousDue || 0).toFixed(2));
                    $('#totalDueCustomers').text(parseInt(json.summary.totalDueCustomers || 0, 10));
                }
                });

                table.search('').draw();
 
                $('#check-all').on('change', function() {
                    $('.row-check').prop('checked', $(this).is(':checked'));
                });

                $('#customer-datatable').on('change', '.row-check', function() {
                    var rowChecks = $('#customer-datatable .row-check');
                    var checked = rowChecks.filter(':checked').length;
                    $('#check-all').prop('checked', rowChecks.length > 0 && checked === rowChecks.length)
                        .prop('indeterminate', checked > 0 && checked < rowChecks.length);
                });

                table.on('draw', function() {
                    $('#check-all').prop({ checked: false, indeterminate: false });
                });

                $('#applyBillingFilters').on('click', function() {
                    table.ajax.reload();
                    if (window.innerWidth < 992) bootstrap.Collapse.getOrCreateInstance(document.getElementById('billingFilters')).hide();
                });

                $('#resetBillingFilters').on('click', function() {
                    $('#zone-filter, #billing-person-filter, #disconnect-date-from, #disconnect-date-to').val('');
                    $('#status-filter').val(defaultStatusFilter);
                    table.search('').ajax.reload();
                });

                $('#headerPrintSelectedButton').on('click', function() {
                    $('#printSelectedButton').trigger('click');
                });

                $('#printSelectedButton').on('click', function() {
                    var ids = $('.row-check:checked').map(function() {
                        return $(this).val();
                    }).get();

                    if (!ids.length) {
                        Swal.fire('Please select at least one invoice to print', '', 'warning');
                        return;
                    }

                    var url = '<?php echo e(route('admin.billings.print')); ?>' + '?' + ids.map(function(id) { return 'ids[]=' + id; }).join('&');
                    window.open(url, '_blank');
                });

                // open payment modal and populate values
                window.openPaymentModal = function(button) {
                    var buttonEl = $(button);
                    var billingId = buttonEl.data('billing-id');
                    var customerId = buttonEl.data('customer-id');
                    var due = buttonEl.data('due');
                    var customerName = buttonEl.data('name') || 'Customer';

                    $('#customer_id').val(customerId);
                    $('#billing_id').val(billingId);
                    $('#due-amount').text(due);
                    $('#paymentCustomerName').text(customerName);
                    $('#amount').val(parseFloat(String(due).replace(/,/g, '')) || 0);
                    $('#discount').val(0);
                    $('#payment_type').val('1');
                    paymentDescriptionTouched = false;

                    // set default payment month to current month
                    var now = new Date();
                    var mm = String(now.getMonth() + 1).padStart(2, '0');
                    var yyyy = now.getFullYear();
                    $('#payment_month').val(yyyy + '-' + mm);
                    updatePaymentDescription(true);
                    $('#paymentModal').modal('show');
                };

                $('#payFullDue').on('click', function() {
                    $('#amount').val(parseFloat(String($('#due-amount').text()).replace(/,/g, '')) || 0).trigger('focus');
                });

                $('#clearPayAmount').on('click', function() {
                    $('#amount').val(0).trigger('focus').select();
                });

                window.openGraceModal = function(button) {
                    var buttonEl = $(button);
                    $('#grace_customer_id').val(buttonEl.data('customer-id'));
                    $('#graceCustomerName').text((buttonEl.data('name') || 'Customer') + ' · ' + (buttonEl.data('code') || ''));
                    $('#graceCurrentDate').text(buttonEl.data('disconnect') || 'Not set');
                    $('#graceExistingUntil').text(buttonEl.data('grace-until') || 'No active grace');
                    $('#grace_days').val(2);
                    $('#grace_reason').val('');
                    $('#grace_send_sms').prop('checked', true);
                    $('#graceExtensionModal').modal('show');
                };

                $('#saveGraceBtn').on('click', function() {
                    var button = $(this);
                    var customerId = $('#grace_customer_id').val();
                    if (!customerId) return;
                    button.prop('disabled', true);
                    axios.post("<?php echo e(url('admin/customers')); ?>/" + customerId + "/grace-extension", {
                        days: $('#grace_days').val(),
                        reason: $('#grace_reason').val(),
                        send_sms: $('#grace_send_sms').is(':checked')
                    }).then(function(response) {
                        Swal.fire('Saved', (response.data.message || 'Grace saved') + ' Grace until: ' + (response.data.grace_until || ''), 'success');
                        $('#graceExtensionModal').modal('hide');
                        table.ajax.reload(null, false);
                    }).catch(function(error) {
                        Swal.fire('Error', error.response?.data?.message || 'Could not save grace extension.', 'error');
                    }).finally(function() {
                        button.prop('disabled', false);
                    });
                });

                // handle disconnect date change
                $(document).on('change', '.disconnect-date', function () {
                    var input = $(this);
                    var date = input.val();
                    var customerId = input.data('customer-id');
                    if (!customerId) return;

                    axios.post('/admin/customers/' + customerId + '/mikrotik-disconnect', {
                        mikrotik_disconnect: date
                    }).then(function (res) {
                        showToast('Disconnect date updated','success');
                    }).catch(function (err) {
                        showToast('Failed to update date','danger');
                    });
                });

                $('#paymentForm').on('submit', function(e) {
                    e.preventDefault();

                    var payload = {
                        customer_id: $('#customer_id').val(),
                        billing_id: $('#billing_id').val(),
                        amount: $('#amount').val(),
                        discount: $('#discount').val(),
                        payment_type: $('#payment_type').val(),
                        discription: $('#discription').val(),
                        payment_month: $('#payment_month').val(),
                        smssend: $('#smssend').is(':checked') ? '1' : '',
                    };

                    var $btn = $('#submit-btn');
                    var amount = parseFloat(payload.amount) || 0;
                    var discount = parseFloat(payload.discount) || 0;
                    if (amount <= 0 && discount <= 0) {
                        Swal.fire('Enter amount', 'Payment or discount: at least one field must be greater than 0.', 'warning');
                        return;
                    }

                    $btn.prop('disabled', true);
                    $btn.find('.btn-label').hide();
                    $btn.find('.btn-loader').removeClass('d-none');

                    axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');
                    axios.post('<?php echo route('admin.billings.pay'); ?>', payload)
                        .then(function(response) {
                            $btn.find('.btn-label').show();
                            $btn.find('.btn-loader').addClass('d-none');
                            $btn.prop('disabled', false);

                            if (response.data && response.data.success) {
                                Swal.fire({
                                    title: 'Payment recorded',
                                    text: response.data.message || '',
                                    icon: 'success',
                                    showCancelButton: true,
                                    confirmButtonText: 'View History',
                                    cancelButtonText: 'Close'
                                }).then(function(res) {
                                    if (res.isConfirmed) {
                                        var custId = response.data.customer_id;
                                        window.open("<?php echo e(url('admin/customers')); ?>/"+custId+"/ledger", '_blank');
                                    }
                                });

                                // refresh table and close modal
                                table.ajax.reload(null, false);
                                $('#paymentModal').modal('hide');
                            } else {
                                Swal.fire('Error', 'Payment not saved', 'error');
                            }
                        })
                        .catch(function(err) {
                            $btn.find('.btn-label').show();
                            $btn.find('.btn-loader').addClass('d-none');
                            $btn.prop('disabled', false);
                            console.error(err);
                            var msg = (err.response && err.response.data && err.response.data.message) ? err.response.data.message : 'Payment failed';
                            Swal.fire('Error', msg, 'error');
                        });
                });

                
            });
        </script>
    <?php $__env->stopPush(); ?>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php /**PATH D:\herd\billing\laravel-app\resources\views/admin/billings/index.blade.php ENDPATH**/ ?>