

<?php $__env->startSection('title', 'Bill Payments'); ?>
<?php $__env->startSection('page-title', 'Bill Payments'); ?>
<?php $__env->startSection('page-subtitle', 'Airtime, data, electricity, cable TV, and internet payment records'); ?>

<?php $__env->startSection('content'); ?>
<?php
    $currency = auth()->user()->tenant->settings['currency'] ?? 'NGN';
    $money = fn ($amount) => $currency.' '.number_format((float) $amount, 2);
    $compactMoney = function ($amount) use ($currency) {
        $amount = (float) $amount;
        $absolute = abs($amount);

        if ($absolute >= 1000000) {
            return $currency.' '.number_format($amount / 1000000, 1).'M';
        }

        if ($absolute >= 1000) {
            return $currency.' '.number_format($amount / 1000, 1).'K';
        }

        return $currency.' '.number_format($amount, 2);
    };
    $serviceIcons = [
        'airtime' => 'bi-phone',
        'data' => 'bi-wifi',
        'electricity' => 'bi-lightning-charge',
        'cable_tv' => 'bi-tv',
        'internet' => 'bi-router',
    ];
    $billDriver = app(\App\Services\PlatformSettings::class)->billPaymentDriver();
    $billLiveProvider = in_array($billDriver, ['vtpass', 'flutterwave'], true);
?>

<section class="section-hero mb-4">
    <div class="section-hero-copy">
        <span>Account center</span>
        <h2>Bill payment desk</h2>
        <p>Record airtime, data, NEPA, cable TV, and internet transactions with cleaner tracking for fees, commissions, tokens, and status updates.</p>
    </div>
    <div class="section-hero-panel">
        <span>Successful volume</span>
        <strong><?php echo e($compactMoney($totalVolume)); ?></strong>
        <small><?php echo e(app_day_month($from)); ?> to <?php echo e(app_date($to)); ?></small>
    </div>
</section>

<div class="section-stat-grid mb-4">
    <div class="section-stat-card">
        <i class="bi bi-check2-circle"></i>
        <span>Successful volume</span>
        <strong><?php echo e($compactMoney($totalVolume)); ?></strong>
        <small>Filtered period</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-percent"></i>
        <span>VTU earnings</span>
        <strong><?php echo e($compactMoney($totalEarnings)); ?></strong>
        <small>Fees and markup from successful bills</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-hourglass-split"></i>
        <span>Pending</span>
        <strong><?php echo e(number_format($pendingCount)); ?></strong>
        <small>Needs follow up</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-grid"></i>
        <span>Services</span>
        <strong><?php echo e(number_format(count($serviceTypes))); ?></strong>
        <small>Airtime, data, NEPA, TV, internet</small>
    </div>
</div>

<div class="service-chip-row mb-4">
    <?php $__currentLoopData = $serviceTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
        <a href="<?php echo e(route('tenant.bill-payments.index', array_merge(request()->query(), ['service_type' => $value]))); ?>" class="service-chip <?php echo e(($filters['service_type'] ?? '') === $value ? 'active' : ''); ?>">
            <i class="bi <?php echo e($serviceIcons[$value] ?? 'bi-receipt'); ?>"></i>
            <span><?php echo e($label); ?></span>
        </a>
    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</div>

<div class="row g-4">
    <?php if(auth()->user()->hasPermission('bill_payments.manage')): ?>
    <div class="col-xl-4">
        <div class="section-form-card sticky-lg-top">
            <div class="section-card-title">
                <span><i class="bi bi-lightning-charge"></i></span>
                <div>
                    <strong><?php echo e($billLiveProvider ? 'Sell bill payment' : 'Record bill payment'); ?></strong>
                    <small><?php echo e($billLiveProvider ? 'Collect payment, then vend through the live provider using your VTU wallet.' : 'Capture member, provider, fee, commission, and token details.'); ?></small>
                </div>
            </div>
            <form method="POST" action="<?php echo e(route('tenant.bill-payments.store')); ?>" class="row g-3">
                <?php echo csrf_field(); ?>
                <div class="col-md-6">
                    <label class="form-label">Service</label>
                    <select name="service_type" id="billServiceType" class="form-select" required>
                        <?php $__currentLoopData = $serviceTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($value); ?>" <?php if(old('service_type', 'airtime') === $value): echo 'selected'; endif; ?>><?php echo e($label); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Provider</label>
                    <select name="provider" id="billProvider" class="form-select" data-current="<?php echo e(old('provider')); ?>" required></select>
                </div>
                <div class="col-12">
                    <label class="form-label">Member</label>
                    <select name="customer_id" class="form-select">
                        <option value="">Walk-in member</option>
                        <?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($customer->id); ?>" <?php if((string) old('customer_id') === (string) $customer->id): echo 'selected'; endif; ?>><?php echo e($customer->fullName()); ?> - <?php echo e($customer->account_number); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Walk-in name</label>
                    <input name="customer_name" value="<?php echo e(old('customer_name')); ?>" class="form-control" placeholder="Optional">
                </div>
                <div class="col-12">
                    <label class="form-label">Phone, meter, smartcard, or account number</label>
                    <input name="customer_identifier" value="<?php echo e(old('customer_identifier')); ?>" class="form-control" required>
                </div>
                <div class="col-12">
                    <label class="form-label">Plan/package</label>
                    <input name="package_name" value="<?php echo e(old('package_name')); ?>" class="form-control" placeholder="<?php echo e($billDriver === 'flutterwave' ? 'BILLER_CODE|ITEM_CODE for Flutterwave packages' : 'Optional'); ?>">
                    <?php if($billDriver === 'flutterwave'): ?>
                        <div class="form-text">For data, cable TV, internet, or exact billers, use Flutterwave format: BILLER_CODE|ITEM_CODE.</div>
                    <?php endif; ?>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Amount</label>
                    <input name="amount" value="<?php echo e(old('amount')); ?>" type="number" step="0.01" min="0.01" class="form-control" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Fee</label>
                    <input name="fee" value="<?php echo e(old('fee', 0)); ?>" type="number" step="0.01" min="0" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Markup / commission</label>
                    <input name="commission" value="<?php echo e(old('commission', 0)); ?>" type="number" step="0.01" min="0" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Payment method</label>
                    <select name="payment_method" class="form-select" required>
                        <?php $__currentLoopData = $paymentMethods; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($value); ?>" <?php if(old('payment_method', 'cash') === $value): echo 'selected'; endif; ?>><?php echo e($label); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <?php if($billLiveProvider): ?>
                    <input type="hidden" name="status" value="<?php echo e(\App\Models\BillPayment::STATUS_PENDING); ?>">
                <?php else: ?>
                    <div class="col-md-6">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select" required>
                            <?php $__currentLoopData = $statuses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($value); ?>" <?php if(old('status', 'successful') === $value): echo 'selected'; endif; ?>><?php echo e($label); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Provider reference</label>
                        <input name="provider_reference" value="<?php echo e(old('provider_reference')); ?>" class="form-control" placeholder="Optional">
                    </div>
                    <div class="col-12">
                        <label class="form-label">Token/PIN</label>
                        <textarea name="token" class="form-control" rows="2" placeholder="Electricity token or recharge PIN"><?php echo e(old('token')); ?></textarea>
                    </div>
                <?php endif; ?>
                <div class="col-12">
                    <label class="form-label">Internal notes</label>
                    <textarea name="notes" class="form-control" rows="2"><?php echo e(old('notes')); ?></textarea>
                </div>
                <div class="col-12 d-grid">
                    <button class="btn btn-primary btn-lg"><i class="bi bi-lightning-charge me-1"></i> <?php echo e($billLiveProvider ? 'Send bill payment' : 'Save bill payment'); ?></button>
                </div>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <div class="<?php echo e(auth()->user()->hasPermission('bill_payments.manage') ? 'col-xl-8' : 'col-xl-12'); ?>">
        <div class="section-data-card">
            <div class="section-card-title">
                <span><i class="bi bi-search"></i></span>
                <div>
                    <strong>Payment records</strong>
                    <small>Search, filter, and update bill payment status.</small>
                </div>
            </div>
            <div class="section-filter-panel">
                <form method="GET" class="row g-2 align-items-end">
                    <div class="col-md-4">
                        <label class="form-label">Search</label>
                        <input name="search" value="<?php echo e($filters['search'] ?? ''); ?>" class="form-control" placeholder="Reference, provider, meter">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Type</label>
                        <select name="service_type" class="form-select">
                            <option value="">All</option>
                            <?php $__currentLoopData = $serviceTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($value); ?>" <?php if(($filters['service_type'] ?? '') === $value): echo 'selected'; endif; ?>><?php echo e($label); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All</option>
                            <?php $__currentLoopData = $statuses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($value); ?>" <?php if(($filters['status'] ?? '') === $value): echo 'selected'; endif; ?>><?php echo e($label); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">From</label>
                        <input name="from" type="date" value="<?php echo e($from->format('Y-m-d')); ?>" class="form-control">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">To</label>
                        <input name="to" type="date" value="<?php echo e($to->format('Y-m-d')); ?>" class="form-control">
                    </div>
                    <div class="col-12 d-flex justify-content-end gap-2">
                        <a href="<?php echo e(route('tenant.bill-payments.index')); ?>" class="btn btn-outline-secondary">Reset</a>
                        <button class="btn btn-primary"><i class="bi bi-funnel me-1"></i> Apply filters</button>
                    </div>
                </form>
            </div>
            <div class="table-responsive">
                <table class="table section-table align-middle mb-0">
                    <thead><tr><th>Date</th><th>Reference</th><th>Service</th><th>Member / Staff</th><th>Amount</th><th>Status</th><th>Actions</th></tr></thead>
                    <tbody>
                    <?php $__empty_1 = true; $__currentLoopData = $billPayments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $payment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <?php
                            $providerMessage = data_get($payment->provider_response, 'message');
                            $billProviderDriver = data_get($payment->provider_response, 'driver');
                            $isLiveProviderPayment = in_array($billProviderDriver, ['vtpass', 'flutterwave'], true);
                        ?>
                        <tr>
                            <td><?php echo e(app_date($payment->created_at)); ?></td>
                            <td>
                                <div class="fw-semibold"><?php echo e($payment->reference); ?></div>
                                <small class="text-muted"><?php echo e($payment->provider_reference ?: 'No provider ref'); ?></small>
                            </td>
                            <td>
                                <div><?php echo e($serviceTypes[$payment->service_type] ?? ucfirst($payment->service_type)); ?></div>
                                <small class="text-muted"><?php echo e($payment->provider); ?> <?php echo e($payment->package_name ? '- '.$payment->package_name : ''); ?></small>
                            </td>
                            <td>
                                <div><?php echo e($payment->customer?->fullName() ?: ($payment->userWallet?->user?->name ?: ($payment->customer_name ?: 'Walk-in'))); ?></div>
                                <small class="text-muted"><?php echo e($payment->user_wallet_id ? 'Staff wallet' : 'Member'); ?> | <?php echo e($payment->customer_identifier); ?></small>
                            </td>
                            <td>
                                <div><?php echo e($money($payment->total_amount)); ?></div>
                                <small class="text-muted">Bill <?php echo e($money($payment->amount)); ?> | Earned <?php echo e($money((float) $payment->fee + (float) $payment->commission)); ?></small>
                            </td>
                            <td><span class="badge text-bg-<?php echo e($payment->status === 'successful' ? 'success' : ($payment->status === 'failed' ? 'danger' : ($payment->status === 'pending' ? 'warning' : 'secondary'))); ?>"><?php echo e(ucfirst($payment->status)); ?></span></td>
                            <?php if(auth()->user()->hasPermission('bill_payments.manage')): ?>
                            <td style="min-width: 260px;">
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Actions</button>
                                    <ul class="dropdown-menu dropdown-menu-end">
                                        <?php if($payment->status !== \App\Models\BillPayment::STATUS_REVERSED): ?>
                                            <?php if($isLiveProviderPayment && $payment->status === \App\Models\BillPayment::STATUS_PENDING): ?>
                                                <li>
                                                    <form method="POST" action="<?php echo e(route('tenant.bill-payments.requery', $payment)); ?>">
                                                        <?php echo csrf_field(); ?>
                                                        <button class="dropdown-item"><i class="bi bi-arrow-repeat me-2"></i>Requery provider</button>
                                                    </form>
                                                </li>
                                            <?php endif; ?>
                                            <li><button class="dropdown-item" type="button" data-bs-toggle="collapse" data-bs-target="#billStatus<?php echo e($payment->id); ?>"><i class="bi bi-pencil-square me-2"></i>Update status</button></li>
                                            <li><button class="dropdown-item text-danger" type="button" data-bs-toggle="modal" data-bs-target="#cancelBillPayment<?php echo e($payment->id); ?>"><i class="bi bi-slash-circle me-2"></i>Cancel</button></li>
                                        <?php else: ?>
                                            <li><span class="dropdown-item-text text-muted small">Reversed by <?php echo e($payment->canceledBy?->name ?? 'admin'); ?></span></li>
                                        <?php endif; ?>
                                    </ul>
                                </div>
                                <?php if($payment->status !== \App\Models\BillPayment::STATUS_REVERSED): ?>
                                    <form method="POST" action="<?php echo e(route('tenant.bill-payments.status', $payment)); ?>" class="bill-status-form collapse mt-2" id="billStatus<?php echo e($payment->id); ?>">
                                        <?php echo csrf_field(); ?>
                                        <?php echo method_field('PATCH'); ?>
                                        <select name="status" class="form-select form-select-sm">
                                            <?php $__currentLoopData = $statuses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <?php if($value === \App\Models\BillPayment::STATUS_REVERSED) continue; ?>
                                                <option value="<?php echo e($value); ?>" <?php if($payment->status === $value): echo 'selected'; endif; ?>><?php echo e($label); ?></option>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </select>
                                        <input name="provider_reference" value="<?php echo e($payment->provider_reference); ?>" class="form-control form-control-sm" placeholder="Provider ref">
                                        <input name="token" value="<?php echo e($payment->token); ?>" class="form-control form-control-sm" placeholder="Token/PIN">
                                        <button class="btn btn-sm btn-outline-primary">Save</button>
                                    </form>
                                <?php endif; ?>
                                <?php if($providerMessage): ?>
                                    <button class="btn btn-link btn-sm px-0 mt-1" type="button" data-bs-toggle="collapse" data-bs-target="#billProviderMessage<?php echo e($payment->id); ?>">
                                        Provider message
                                    </button>
                                    <div class="collapse small text-muted" id="billProviderMessage<?php echo e($payment->id); ?>">
                                        <?php echo e($providerMessage); ?>

                                        <?php if(data_get($payment->provider_response, 'refunded')): ?>
                                            <div class="text-success">Local balance refunded.</div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <?php else: ?>
                            <td class="text-muted">View only</td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <tr><td colspan="7" class="text-center text-muted py-5">No bill payment records found.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="p-3"><?php echo e($billPayments->links()); ?></div>
        </div>
    </div>
</div>

<?php if(auth()->user()->hasPermission('bill_payments.manage')): ?>
    <?php $__currentLoopData = $billPayments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $payment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
        <?php if($payment->status !== \App\Models\BillPayment::STATUS_REVERSED): ?>
            <div class="modal fade" id="cancelBillPayment<?php echo e($payment->id); ?>" tabindex="-1" aria-labelledby="cancelBillPayment<?php echo e($payment->id); ?>Label" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content border-0 shadow">
                        <form method="POST" action="<?php echo e(route('tenant.bill-payments.cancel', $payment)); ?>">
                            <?php echo csrf_field(); ?>
                            <div class="modal-header">
                                <div>
                                    <h2 class="modal-title h5" id="cancelBillPayment<?php echo e($payment->id); ?>Label">Cancel bill payment</h2>
                                    <div class="text-muted small"><?php echo e($payment->reference); ?> | <?php echo e($serviceTypes[$payment->service_type] ?? ucfirst($payment->service_type)); ?> | <?php echo e($money($payment->total_amount)); ?></div>
                                </div>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <label class="form-label">Cancellation reason</label>
                                <textarea name="canceled_reason" class="form-control" rows="3" required></textarea>
                                <div class="form-text">The bill payment will be marked as reversed and kept in history.</div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                                <button class="btn btn-danger">Cancel bill payment</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const providersByType = <?php echo json_encode($providers, 15, 512) ?>;
    const serviceSelect = document.getElementById('billServiceType');
    const providerSelect = document.getElementById('billProvider');

    const fillProviders = () => {
        if (!serviceSelect || !providerSelect) return;
        const current = providerSelect.dataset.current;
        const providers = providersByType[serviceSelect.value] || [];
        providerSelect.innerHTML = providers.map((provider) => {
            const selected = provider === current ? 'selected' : '';
            return `<option value="${provider}" ${selected}>${provider}</option>`;
        }).join('');
        providerSelect.dataset.current = providerSelect.value;
    };

    serviceSelect?.addEventListener('change', () => {
        providerSelect.dataset.current = '';
        fillProviders();
    });

    fillProviders();
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Polite hp\Documents\Codex\2026-05-08\build-a-complete-production-ready-saas\microfinance-saas\resources\views\tenant\bill-payments\index.blade.php ENDPATH**/ ?>