<?php $__env->startSection('title', 'Message Units'); ?>
<?php $__env->startSection('page-title', 'Message Units'); ?>
<?php $__env->startSection('page-subtitle', 'Buy SMS and WhatsApp units, track usage, and control member message charges'); ?>

<?php $__env->startSection('content'); ?>
<?php
    $currency = $tenant->settings['currency'] ?? 'NGN';
    $money = fn ($amount) => $currency.' '.number_format((float) $amount, 2);
    $walletByChannel = $wallets->keyBy('channel');
    $smsWallet = $walletByChannel['sms'] ?? null;
    $whatsappWallet = $walletByChannel['whatsapp'] ?? null;
    $pendingTopups = $topups->getCollection()->where('status', 'pending')->count();
    $memberCharges = (float) $wallets->sum(fn ($wallet) => (float) $wallet->total_member_charges);
    $usedCost = (float) $wallets->sum(fn ($wallet) => (float) $wallet->total_used_cost);
    $grossProfit = $memberCharges - $usedCost;
?>

<section class="section-hero mb-4">
    <div class="section-hero-copy">
        <span>Communication wallet</span>
        <h2>Fund SMS and WhatsApp before sending</h2>
        <p>Every SMS or WhatsApp notification uses prepaid units. When a wallet reaches zero, the system blocks that channel until new units are credited.</p>
    </div>
    <div class="section-hero-panel">
        <span>Wallet status</span>
        <strong><?php echo e(number_format((int) ($smsWallet?->balance_units ?? 0))); ?> SMS</strong>
        <small><?php echo e(number_format((int) ($whatsappWallet?->balance_units ?? 0))); ?> WhatsApp units available</small>
    </div>
</section>

<div class="section-stat-grid mb-4">
    <div class="section-stat-card">
        <i class="bi bi-phone"></i>
        <span>SMS units</span>
        <strong><?php echo e(number_format((int) ($smsWallet?->balance_units ?? 0))); ?></strong>
        <small><?php echo e($money($platformPrices['sms'] ?? 0)); ?> per unit</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-whatsapp"></i>
        <span>WhatsApp units</span>
        <strong><?php echo e(number_format((int) ($whatsappWallet?->balance_units ?? 0))); ?></strong>
        <small><?php echo e($money($platformPrices['whatsapp'] ?? 0)); ?> per unit</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-hourglass-split"></i>
        <span>Pending top-ups</span>
        <strong><?php echo e(number_format($pendingTopups)); ?></strong>
        <small>Awaiting approval or gateway confirmation</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-cash-coin"></i>
        <span>Message profit</span>
        <strong><?php echo e($money($grossProfit)); ?></strong>
        <small><?php echo e($money($memberCharges)); ?> revenue less <?php echo e($money($usedCost)); ?> cost</small>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-4">
        <div class="section-form-card mb-4">
            <div class="section-card-title">
                <span><i class="bi bi-credit-card"></i></span>
                <div>
                    <strong>Buy units online</strong>
                    <small>Gateway payments credit units automatically after confirmation.</small>
                </div>
            </div>
            <form method="POST" action="<?php echo e(route('tenant.communication-units.gateway.start')); ?>" class="row g-3">
                <?php echo csrf_field(); ?>
                <div class="col-12">
                    <label class="form-label">Channel</label>
                    <select name="channel" class="form-select" required>
                        <?php $__currentLoopData = $channels; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $channel => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($channel); ?>"><?php echo e($label); ?> - <?php echo e($money($platformPrices[$channel] ?? 0)); ?>/unit</option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Units</label>
                    <input name="units" type="number" min="1" value="<?php echo e(old('units', 100)); ?>" class="form-control" required>
                </div>
                <div class="col-12 d-grid">
                    <button class="btn btn-success" <?php if(! $gatewayEnabled): echo 'disabled'; endif; ?>><i class="bi bi-lightning-charge me-1"></i> Pay and credit units</button>
                </div>
                <?php if(! $gatewayEnabled): ?>
                    <div class="col-12"><div class="alert alert-warning small mb-0">Online payment is not enabled by the Super Admin yet. Use manual payment instead.</div></div>
                <?php endif; ?>
            </form>
        </div>

        <div class="section-form-card">
            <div class="section-card-title">
                <span><i class="bi bi-upload"></i></span>
                <div>
                    <strong>Manual payment</strong>
                    <small>Submit proof and wait for Super Admin approval.</small>
                </div>
            </div>
            <form method="POST" action="<?php echo e(route('tenant.communication-units.manual.store')); ?>" enctype="multipart/form-data" class="row g-3" data-manual-unit-form>
                <?php echo csrf_field(); ?>
                <div class="col-12">
                    <label class="form-label">Channel</label>
                    <select name="channel" class="form-select" required>
                        <?php $__currentLoopData = $channels; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $channel => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($channel); ?>"><?php echo e($label); ?> - <?php echo e($money($platformPrices[$channel] ?? 0)); ?>/unit</option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Units</label>
                    <input name="units" type="number" min="1" value="<?php echo e(old('units', 100)); ?>" class="form-control" required>
                </div>
                <div class="col-12" data-payment-proof-camera>
                    <label class="form-label">Payment proof <span class="text-danger">*</span></label>
                    <input name="proof_camera" type="hidden" value="<?php echo e(old('proof_camera')); ?>" data-proof-payload>
                    <input name="proof" type="file" accept="image/*,application/pdf" class="visually-hidden" data-proof-file>
                    <div class="border rounded-3 p-3 bg-light">
                        <div class="d-grid gap-2">
                            <button type="button" class="btn btn-outline-primary" data-proof-upload>
                                <i class="bi bi-upload me-1"></i> Upload image or receipt
                            </button>
                            <button type="button" class="btn btn-outline-secondary d-none" data-proof-device-camera>
                                <i class="bi bi-camera me-1" data-proof-camera-icon></i>
                                <span data-proof-camera-label>Snap with camera</span>
                            </button>
                        </div>
                        <video class="w-100 rounded-3 mt-3 d-none" style="max-height: 260px; object-fit: cover; background:#111;" autoplay muted playsinline data-proof-video></video>
                        <canvas class="d-none" data-proof-canvas></canvas>
                        <img class="img-fluid rounded-3 border mt-3 d-none" alt="Payment proof preview" data-proof-preview>
                        <div class="rounded-3 border bg-white mt-3 p-3 d-none" data-proof-file-preview>
                            <div class="fw-semibold"><i class="bi bi-file-earmark-check me-1"></i> Receipt selected</div>
                            <small class="text-muted" data-proof-file-name></small>
                        </div>
                        <div class="d-flex gap-2 mt-3">
                            <button type="button" class="btn btn-success btn-sm d-none" data-proof-capture>
                                <i class="bi bi-camera me-1"></i> Capture photo
                            </button>
                            <button type="button" class="btn btn-outline-danger btn-sm d-none" data-proof-retake>
                                <i class="bi bi-arrow-counterclockwise me-1"></i> Retake
                            </button>
                        </div>
                        <div class="small text-muted mt-2" data-proof-status>Payment proof is required for manual unit purchase.</div>
                    </div>
                    <?php $__errorArgs = ['proof'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <div class="text-danger small mt-1"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    <?php $__errorArgs = ['proof_camera'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <div class="text-danger small mt-1"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>
                <div class="col-12">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="3" placeholder="Bank transfer reference or payment notes"><?php echo e(old('notes')); ?></textarea>
                </div>
                <div class="col-12 d-grid">
                    <button class="btn btn-primary"><i class="bi bi-send me-1"></i> Submit for approval</button>
                </div>
            </form>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="section-workspace">
            <div class="section-tabbar">
                <ul class="nav section-tabs" role="tablist">
                    <li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#unit-wallets-pane" type="button">Wallets</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#unit-topups-pane" type="button">Top-ups</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#unit-ledger-pane" type="button">Usage ledger</button></li>
                </ul>
            </div>
            <div class="tab-content">
                <div class="tab-pane fade show active" id="unit-wallets-pane" role="tabpanel" tabindex="0">
                    <div class="section-pane-head">
                        <div><span>Balances</span><h3>Current communication wallet</h3></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table section-table mb-0">
                            <thead><tr><th>Channel</th><th>Balance</th><th>Wallet value</th><th>Total credited</th><th>Total used</th><th>Cost used</th><th>Member charges</th></tr></thead>
                            <tbody>
                            <?php $__currentLoopData = $wallets; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $wallet): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr>
                                    <td><span class="badge text-bg-light border"><?php echo e($wallet->channelLabel()); ?></span></td>
                                    <td class="fw-semibold"><?php echo e(number_format($wallet->balance_units)); ?></td>
                                    <td><?php echo e($money($wallet->cost_balance)); ?></td>
                                    <td><?php echo e(number_format($wallet->total_credited_units)); ?></td>
                                    <td><?php echo e(number_format($wallet->total_used_units)); ?></td>
                                    <td><?php echo e($money($wallet->total_used_cost)); ?></td>
                                    <td><?php echo e($money($wallet->total_member_charges)); ?></td>
                                </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="unit-topups-pane" role="tabpanel" tabindex="0">
                    <div class="section-pane-head">
                        <div><span>Purchases</span><h3>Unit payment history</h3></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table section-table mb-0">
                            <thead><tr><th>Reference</th><th>Channel</th><th>Units</th><th>Amount</th><th>Status</th><th>Date</th></tr></thead>
                            <tbody>
                            <?php $__empty_1 = true; $__currentLoopData = $topups; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $topup): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <tr>
                                    <td>
                                        <div class="fw-semibold"><?php echo e($topup->reference); ?></div>
                                        <small class="text-muted"><?php echo e(ucfirst($topup->payment_channel)); ?></small>
                                    </td>
                                    <td><?php echo e($topup->channelLabel()); ?></td>
                                    <td><?php echo e(number_format($topup->units)); ?></td>
                                    <td><?php echo e($money($topup->amount)); ?></td>
                                    <td><span class="badge text-bg-<?php echo e($topup->status === 'approved' ? 'success' : ($topup->status === 'rejected' ? 'danger' : 'warning')); ?>"><?php echo e(ucfirst($topup->status)); ?></span></td>
                                    <td><?php echo e(app_datetime($topup->created_at)); ?></td>
                                </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <tr><td colspan="6" class="text-center text-muted py-4">No unit payments yet.</td></tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="p-3"><?php echo e($topups->links()); ?></div>
                </div>

                <div class="tab-pane fade" id="unit-ledger-pane" role="tabpanel" tabindex="0">
                    <div class="section-pane-head">
                        <div><span>Ledger</span><h3>Credits, usage, refunds, and member charges</h3></div>
                    </div>
                    <div class="table-responsive">
                        <table class="table section-table mb-0">
                            <thead><tr><th>Date</th><th>Channel</th><th>Type</th><th>Units</th><th>Balance</th><th>Member</th><th>Charge</th><th>Cost</th></tr></thead>
                            <tbody>
                            <?php $__empty_1 = true; $__currentLoopData = $transactions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $transaction): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <tr>
                                    <td><?php echo e(app_datetime($transaction->created_at)); ?></td>
                                    <td><?php echo e($transaction->channelLabel()); ?></td>
                                    <td><span class="badge text-bg-light border"><?php echo e(ucfirst($transaction->type)); ?></span></td>
                                    <td><?php echo e($transaction->direction === 'debit' ? '-' : '+'); ?><?php echo e(number_format($transaction->units)); ?></td>
                                    <td><?php echo e(number_format($transaction->balance_after)); ?></td>
                                    <td><?php echo e($transaction->customer?->fullName() ?? '-'); ?></td>
                                    <td><?php echo e($money($transaction->amount)); ?></td>
                                    <td><?php echo e($money($transaction->cost_amount)); ?></td>
                                </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <tr><td colspan="8" class="text-center text-muted py-4">No unit activity yet.</td></tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="p-3"><?php echo e($transactions->links()); ?></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const proofBox = document.querySelector('[data-payment-proof-camera]');
    if (! proofBox) return;

    const form = proofBox.closest('[data-manual-unit-form]');
    const fileInput = proofBox.querySelector('[data-proof-file]');
    const payloadInput = proofBox.querySelector('[data-proof-payload]');
    const uploadButton = proofBox.querySelector('[data-proof-upload]');
    const deviceCameraButton = proofBox.querySelector('[data-proof-device-camera]');
    const cameraIcon = proofBox.querySelector('[data-proof-camera-icon]');
    const cameraLabel = proofBox.querySelector('[data-proof-camera-label]');
    const captureButton = proofBox.querySelector('[data-proof-capture]');
    const retakeButton = proofBox.querySelector('[data-proof-retake]');
    const video = proofBox.querySelector('[data-proof-video]');
    const canvas = proofBox.querySelector('[data-proof-canvas]');
    const preview = proofBox.querySelector('[data-proof-preview]');
    const filePreview = proofBox.querySelector('[data-proof-file-preview]');
    const fileName = proofBox.querySelector('[data-proof-file-name]');
    const status = proofBox.querySelector('[data-proof-status]');
    let stream = null;
    let cameraMode = null;

    const setStatus = (message, tone = 'muted') => {
        status.className = `small text-${tone} mt-2`;
        status.textContent = message;
    };

    const stopCamera = () => {
        if (stream) {
            stream.getTracks().forEach((track) => track.stop());
            stream = null;
        }

        video.srcObject = null;
        video.classList.add('d-none');
        captureButton.classList.add('d-none');
    };

    const showPreview = (src, message) => {
        preview.src = src;
        preview.classList.remove('d-none');
        filePreview.classList.add('d-none');
        retakeButton.classList.remove('d-none');
        setStatus(message, 'success');
    };

    const showFilePreview = (file, message) => {
        preview.removeAttribute('src');
        preview.classList.add('d-none');
        fileName.textContent = `${file.name} (${Math.ceil(file.size / 1024)} KB)`;
        filePreview.classList.remove('d-none');
        retakeButton.classList.remove('d-none');
        setStatus(message, 'success');
    };

    const clearProof = () => {
        payloadInput.value = '';
        fileInput.value = '';
        preview.removeAttribute('src');
        preview.classList.add('d-none');
        filePreview.classList.add('d-none');
        fileName.textContent = '';
        retakeButton.classList.add('d-none');
        setStatus('Payment proof is required for manual unit purchase.');
    };

    const openFilePicker = (cameraCapture = false) => {
        stopCamera();
        fileInput.value = '';
        fileInput.setAttribute('accept', cameraCapture ? 'image/*' : 'image/*,application/pdf');

        if (cameraCapture) {
            fileInput.setAttribute('capture', 'environment');
        } else {
            fileInput.removeAttribute('capture');
        }

        fileInput.click();
    };

    const isTouchCameraDevice = window.matchMedia('(hover: none) and (pointer: coarse)').matches
        || /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
    const hasBrowserCamera = Boolean(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);

    if (isTouchCameraDevice) {
        cameraMode = 'phone';
        cameraIcon.className = 'bi bi-phone me-1';
        cameraLabel.textContent = 'Snap with phone camera';
        deviceCameraButton.classList.remove('d-none');
    } else if (hasBrowserCamera) {
        cameraMode = 'computer';
        cameraIcon.className = 'bi bi-camera-video me-1';
        cameraLabel.textContent = 'Snap with computer camera';
        deviceCameraButton.classList.remove('d-none');
    }

    if (payloadInput.value) {
        showPreview(payloadInput.value, 'Payment proof photo captured.');
    }

    uploadButton.addEventListener('click', () => openFilePicker(false));

    deviceCameraButton.addEventListener('click', async () => {
        if (cameraMode === 'phone') {
            openFilePicker(true);
            return;
        }

        clearProof();

        try {
            stream = await navigator.mediaDevices.getUserMedia({
                audio: false,
                video: {
                    facingMode: { ideal: 'environment' },
                    width: { ideal: 1280 },
                    height: { ideal: 720 },
                },
            });

            video.srcObject = stream;
            video.classList.remove('d-none');
            captureButton.classList.remove('d-none');
            setStatus('Camera ready. Position the payment receipt or transfer proof, then capture.');
        } catch (error) {
            setStatus('Camera could not open. Please allow camera access or upload the receipt/image instead.', 'danger');
        }
    });

    captureButton.addEventListener('click', () => {
        if (! stream || ! video.videoWidth) {
            setStatus('Camera is not ready yet. Please wait a moment and try again.', 'danger');
            return;
        }

        const maxWidth = 1280;
        const scale = Math.min(1, maxWidth / video.videoWidth);
        canvas.width = Math.round(video.videoWidth * scale);
        canvas.height = Math.round(video.videoHeight * scale);
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

        const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
        payloadInput.value = dataUrl;
        fileInput.value = '';
        stopCamera();
        showPreview(dataUrl, 'Payment proof photo captured.');
    });

    retakeButton.addEventListener('click', () => {
        stopCamera();
        clearProof();
    });

    fileInput.addEventListener('change', () => {
        const file = fileInput.files && fileInput.files[0];
        payloadInput.value = '';

        if (! file) {
            clearProof();
            return;
        }

        if (! file.type.startsWith('image/') && file.type !== 'application/pdf') {
            clearProof();
            setStatus('Please upload a JPG, PNG, or PDF receipt.', 'danger');
            return;
        }

        if (file.type === 'application/pdf') {
            showFilePreview(file, 'Receipt PDF selected.');
            return;
        }

        const reader = new FileReader();
        reader.addEventListener('load', () => showPreview(reader.result, 'Payment proof image selected.'));
        reader.readAsDataURL(file);
    });

    form.addEventListener('submit', (event) => {
        const hasCapturedPhoto = payloadInput.value.trim() !== '';
        const hasPhonePhoto = fileInput.files && fileInput.files.length > 0;

        if (! hasCapturedPhoto && ! hasPhonePhoto) {
            event.preventDefault();
            stopCamera();
            setStatus('Upload a receipt/image or snap payment proof before submitting this manual payment.', 'danger');
            proofBox.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    });
});
</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\communication-units\index.blade.php ENDPATH**/ ?>