<?php $__env->startSection('title','Disbursement Management'); ?>
<?php $__env->startSection('subtitle','Review completed paid consultations and release professional payouts.'); ?>
<?php $__env->startSection('content'); ?>
<div class="payout-stats">
    <article>
        <span class="payout-icon"><i data-lucide="wallet-cards"></i></span>
        <div><p>Ready for Release</p><strong>₱<?php echo e(number_format($stats['eligible_amount'],2)); ?></strong><small><?php echo e(number_format($stats['eligible_count'])); ?> eligible bookings</small></div>
    </article>
    <article>
        <span class="payout-icon"><i data-lucide="badge-check"></i></span>
        <div><p>Total Payouts</p><strong>₱<?php echo e(number_format($stats['paid_amount'],2)); ?></strong><small><?php echo e(number_format($stats['payout_count'])); ?> payout records</small></div>
    </article>
    <article class="payout-highlight">
        <span class="payout-icon"><i data-lucide="shield-check"></i></span>
        <div><p>Release Safeguard</p><strong>Verified</strong><small>Paid and closed bookings only</small></div>
    </article>
</div>

<form class="disbursement-filter" method="get" action="<?php echo e(route('disbursements')); ?>">
    <div class="filter-heading"><span><i data-lucide="list-filter"></i></span><div><b>Filter release queue</b><small>Find bookings using the professional name and consultation date.</small></div></div>
    <label><span>Professional name</span><div class="input-icon"><i data-lucide="search"></i><input name="professional" value="<?php echo e(request('professional')); ?>" placeholder="Search professional name"></div></label>
    <label><span>Date from</span><input type="date" name="date_from" value="<?php echo e(request('date_from')); ?>"></label>
    <label><span>Date to</span><input type="date" name="date_to" value="<?php echo e(request('date_to')); ?>"></label>
    <button class="filter-button"><i data-lucide="sliders-horizontal"></i>Apply filters</button>
    <?php if(request()->hasAny(['professional','date_from','date_to'])): ?><a class="clear-filter" href="<?php echo e(route('disbursements')); ?>">Clear</a><?php endif; ?>
</form>

<section class="payout-panel">
    <div class="payout-panel-head">
        <div><h2>Eligible Bookings</h2><p>Select one or more bookings to release. Separate payout records are automatically created for each professional.</p></div>
        <span><?php echo e(number_format($eligible->total())); ?> ready</span>
    </div>
    <form method="post" action="<?php echo e(route('disbursements.release')); ?>" id="release-form" enctype="multipart/form-data"><?php echo csrf_field(); ?>
        <div class="table-scroll">
            <table class="payout-table">
                <thead><tr><th class="check-column"><input type="checkbox" id="select-all" aria-label="Select all visible bookings"></th><th>Professional</th><th>Client</th><th>Consultation</th><th>Closed</th><th class="amount-column">Amount</th></tr></thead>
                <tbody>
                <?php $__empty_1 = true; $__currentLoopData = $eligible; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $booking): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                    <?php
                        $professionalName=$booking->professional?->user?->profile?->full_name??'Professional';
                        $clientName=$booking->client?->profile?->full_name??'Client';
                        $color=$booking->professional?->profession?->color_hex??'#7bd300';
                        $professionalImage=trim((string)($booking->professional?->user?->profile?->image??''));
                        $professionalImageUrl=$professionalImage!==''?(Illuminate\Support\Str::startsWith($professionalImage,['http://','https://'])?$professionalImage:rtrim(config('admin.api_url'),'/').'/storage/users/'.$booking->professional?->user_id.'/'.ltrim($professionalImage,'/')):null;
                        $clientImage=trim((string)($booking->client?->profile?->image??''));
                        $clientImageUrl=$clientImage!==''?(Illuminate\Support\Str::startsWith($clientImage,['http://','https://'])?$clientImage:rtrim(config('admin.api_url'),'/').'/storage/users/'.$booking->client_id.'/'.ltrim($clientImage,'/')):null;
                    ?>
                    <tr>
                        <td class="check-column"><input class="booking-check" type="checkbox" name="bookings[]" value="<?php echo e($booking->id); ?>" data-amount="<?php echo e($booking->payoutAmount()); ?>" data-professional-id="<?php echo e($booking->professional_id); ?>" data-professional-name="<?php echo e($professionalName); ?>" aria-label="Select booking <?php echo e($booking->uuid); ?>"></td>
                        <td><div class="user-cell"><div class="avatar payout-avatar" style="--avatar-border:<?php echo e($color); ?>"><?php if($professionalImageUrl): ?><img src="<?php echo e($professionalImageUrl); ?>" alt="<?php echo e($professionalName); ?>" loading="lazy" onerror="this.hidden=true;this.nextElementSibling.hidden=false"><span hidden><?php echo e(strtoupper(substr($professionalName,0,1))); ?></span><?php else: ?><span><?php echo e(strtoupper(substr($professionalName,0,1))); ?></span><?php endif; ?></div><div><b><?php echo e($professionalName); ?></b><span><?php echo e($booking->professional?->profession?->name??'No profession'); ?></span></div></div></td>
                        <td><div class="user-cell payout-client"><div class="avatar payout-avatar client-avatar"><?php if($clientImageUrl): ?><img src="<?php echo e($clientImageUrl); ?>" alt="<?php echo e($clientName); ?>" loading="lazy" onerror="this.hidden=true;this.nextElementSibling.hidden=false"><span hidden><?php echo e(strtoupper(substr($clientName,0,1))); ?></span><?php else: ?><span><?php echo e(strtoupper(substr($clientName,0,1))); ?></span><?php endif; ?></div><div><b><?php echo e($clientName); ?></b><small>#<?php echo e(strtoupper(substr($booking->uuid,0,8))); ?></small></div></div></td>
                        <td><b><?php echo e($booking->date?->format('M d, Y')??'On-demand'); ?></b><small><?php echo e($booking->time?:ucfirst($booking->type)); ?></small></td>
                        <td><?php echo e($booking->consultation_closed_at?->format('M d, Y')); ?><small><?php echo e($booking->consultation_closed_at?->format('g:i A')); ?></small></td>
                        <td class="amount-column"><b>₱<?php echo e(number_format($booking->payoutAmount(),2)); ?></b><small>Net payout</small></td>
                    </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                    <tr><td colspan="6" class="empty">No paid and closed bookings match this professional and date range.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php if($eligible->count()): ?>
        <div class="proof-upload-area" id="proof-upload-area" hidden>
            <div class="proof-heading"><i data-lucide="receipt-text"></i><div><b>Proof of payment required</b><span>Upload one JPG, PNG, or PDF up to 10MB for every professional invoice.</span></div></div>
            <div class="proof-inputs" id="proof-inputs"></div>
        </div>
        <div class="release-bar">
            <div><span id="selected-count">0 bookings selected</span><strong id="selected-total">₱0.00</strong></div>
            <button type="submit" id="release-button" disabled><i data-lucide="banknote-arrow-up"></i>Disburse Payment</button>
        </div>
        <?php endif; ?>
    </form>
    <div class="table-footer"><span>Showing <?php echo e($eligible->firstItem()??0); ?> to <?php echo e($eligible->lastItem()??0); ?> of <?php echo e(number_format($eligible->total())); ?> eligible bookings</span><?php echo e($eligible->onEachSide(1)->links('vendor.pagination.default')); ?></div>
</section>

<section class="payout-panel payout-history">
    <div class="payout-panel-head"><div><h2>Payout History</h2><p>Released payments grouped by professional.</p></div><span><?php echo e(number_format($stats['payout_count'])); ?> released</span></div>
    <div class="table-scroll"><table class="payout-table"><thead><tr><th>Invoice</th><th>Professional</th><th>Bookings</th><th>Released date</th><th>Status</th><th class="amount-column">Amount</th><th>Actions</th></tr></thead><tbody>
        <?php $__empty_1 = true; $__currentLoopData = $history; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $payout): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
            <?php
                $name=$payout->professional?->user?->profile?->full_name??'Professional';
                $color=$payout->professional?->profession?->color_hex??'#7bd300';
                $image=trim((string)($payout->professional?->user?->profile?->image??''));
                $imageUrl=$image!==''?(Illuminate\Support\Str::startsWith($image,['http://','https://'])?$image:rtrim(config('admin.api_url'),'/').'/storage/users/'.$payout->professional?->user_id.'/'.ltrim($image,'/')):null;
            ?>
            <tr><td><a class="invoice-link" href="<?php echo e(route('disbursements.invoice',$payout)); ?>"><b><?php echo e($payout->reference?:'PAYOUT-'.$payout->id); ?></b><small>View invoice</small></a></td><td><div class="user-cell"><div class="avatar payout-avatar" style="--avatar-border:<?php echo e($color); ?>"><?php if($imageUrl): ?><img src="<?php echo e($imageUrl); ?>" alt="<?php echo e($name); ?>" loading="lazy" onerror="this.hidden=true;this.nextElementSibling.hidden=false"><span hidden><?php echo e(strtoupper(substr($name,0,1))); ?></span><?php else: ?><span><?php echo e(strtoupper(substr($name,0,1))); ?></span><?php endif; ?></div><div><b><?php echo e($name); ?></b><span><?php echo e($payout->professional?->profession?->name??'No profession'); ?></span></div></div></td><td><?php echo e(number_format($payout->bookings_count)); ?> consultation(s)</td><td><?php echo e($payout->paid_at?->format('M d, Y')??'—'); ?><small><?php echo e($payout->paid_at?->format('g:i A')); ?></small></td><td><span class="payout-status <?php echo e($payout->status); ?>"><i></i><?php echo e(ucfirst($payout->status)); ?></span></td><td class="amount-column"><b>₱<?php echo e(number_format($payout->amount,2)); ?></b></td><td><div class="payout-actions"><a title="View payout details" href="<?php echo e(route('disbursements.show',$payout)); ?>"><i data-lucide="eye"></i></a><a title="View invoice" href="<?php echo e(route('disbursements.invoice',$payout)); ?>"><i data-lucide="receipt-text"></i></a><a title="Download invoice" href="<?php echo e(route('disbursements.invoice.download',$payout)); ?>"><i data-lucide="download"></i></a></div></td></tr>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?> <tr><td colspan="7" class="empty">No payout history is available yet.</td></tr> <?php endif; ?>
    </tbody></table></div>
    <div class="table-footer"><span>Showing <?php echo e($history->firstItem()??0); ?> to <?php echo e($history->lastItem()??0); ?> of <?php echo e(number_format($history->total())); ?> payouts</span><?php echo e($history->onEachSide(1)->links('vendor.pagination.default')); ?></div>
</section>
<dialog class="disbursement-confirm" id="disbursement-confirm">
    <div class="confirm-icon"><i data-lucide="hand-coins"></i></div>
    <button type="button" class="confirm-close" id="confirm-close" aria-label="Close"><i data-lucide="x"></i></button>
    <span class="confirm-eyebrow">PAYMENT RELEASE</span>
    <h2>Confirm disbursement</h2>
    <p>Review the payout summary before releasing payment. An invoice and email will be created separately for every professional.</p>
    <div class="confirm-summary">
        <div><span>Total payout</span><strong id="confirm-total">₱0.00</strong></div>
        <div><span>Selected bookings</span><strong id="confirm-bookings">0</strong></div>
        <div><span>Professional invoices</span><strong id="confirm-professionals">0</strong></div>
    </div>
    <div class="confirm-note"><i data-lucide="shield-check"></i><span>Only paid and completed consultations will be released. This action cannot be reversed from this screen.</span></div>
    <footer><button type="button" class="confirm-cancel" id="confirm-cancel">Cancel</button><button type="button" class="confirm-release" id="confirm-release"><i data-lucide="banknote-arrow-up"></i>Confirm & release</button></footer>
</dialog>
<script>
(() => {
    const checks = [...document.querySelectorAll('.booking-check')];
    const selectAll = document.getElementById('select-all');
    const button = document.getElementById('release-button');
    const count = document.getElementById('selected-count');
    const total = document.getElementById('selected-total');
    const proofArea = document.getElementById('proof-upload-area');
    const proofInputs = document.getElementById('proof-inputs');
    const proofFiles = new Map();
    const form = document.getElementById('release-form');
    const confirmDialog = document.getElementById('disbursement-confirm');
    let releaseConfirmed = false;
    const update = () => {
        const selected = checks.filter(check => check.checked);
        if (proofInputs) {
            proofInputs.querySelectorAll('input[type=file]').forEach(input => { if (input.files[0]) proofFiles.set(input.dataset.professionalId, input.files[0]); });
            const professionals = new Map(selected.map(check => [check.dataset.professionalId, check.dataset.professionalName]));
            proofInputs.innerHTML = '';
            professionals.forEach((name, id) => {
                const label = document.createElement('label');
                label.className = 'proof-field';
                label.innerHTML = '<span></span><div><i data-lucide="upload-cloud"></i><em>Choose proof file</em><small>JPG, PNG, or PDF</small></div>';
                label.querySelector('span').textContent = name;
                const input = document.createElement('input');
                input.type = 'file'; input.name = `proofs[${id}]`; input.accept = '.jpg,.jpeg,.png,.pdf'; input.required = true; input.dataset.professionalId = id;
                if (proofFiles.has(id)) { const transfer = new DataTransfer(); transfer.items.add(proofFiles.get(id)); input.files = transfer.files; label.querySelector('em').textContent = proofFiles.get(id).name; }
                input.addEventListener('change', () => {
                    const file = input.files[0];
                    input.setCustomValidity('');
                    if (!file) return;
                    if (file.size > 10 * 1024 * 1024) {
                        input.setCustomValidity('Proof of payment must not exceed 10 MB.');
                        label.querySelector('em').textContent = 'File exceeds 10 MB';
                        proofFiles.delete(id);
                        input.reportValidity();
                        return;
                    }
                    proofFiles.set(id, file);
                    label.querySelector('em').textContent = file.name;
                });
                label.appendChild(input); proofInputs.appendChild(label);
            });
            proofArea.hidden = professionals.size === 0;
            lucide.createIcons();
        }
        if (count) count.textContent = `${selected.length} booking${selected.length === 1 ? '' : 's'} selected`;
        if (total) total.textContent = new Intl.NumberFormat('en-PH', {style:'currency', currency:'PHP'}).format(selected.reduce((sum, check) => sum + Number(check.dataset.amount), 0));
        if (button) button.disabled = selected.length === 0;
        if (selectAll) { selectAll.checked = checks.length > 0 && selected.length === checks.length; selectAll.indeterminate = selected.length > 0 && selected.length < checks.length; }
    };
    selectAll?.addEventListener('change', () => { checks.forEach(check => check.checked = selectAll.checked); update(); });
    checks.forEach(check => check.addEventListener('change', update));
    form?.addEventListener('submit', event => {
        if (releaseConfirmed) {
            if (button) { button.disabled = true; button.innerHTML = 'Processing disbursement…'; }
            return;
        }
        event.preventDefault();
        const selected = checks.filter(check => check.checked);
        document.getElementById('confirm-total').textContent = total?.textContent || '₱0.00';
        document.getElementById('confirm-bookings').textContent = selected.length;
        document.getElementById('confirm-professionals').textContent = new Set(selected.map(check => check.dataset.professionalId)).size;
        confirmDialog?.showModal();
    });
    const closeDialog = () => confirmDialog?.close();
    document.getElementById('confirm-close')?.addEventListener('click', closeDialog);
    document.getElementById('confirm-cancel')?.addEventListener('click', closeDialog);
    document.getElementById('confirm-release')?.addEventListener('click', () => { releaseConfirmed = true; closeDialog(); form?.requestSubmit(); });
    confirmDialog?.addEventListener('click', event => { if (event.target === confirmDialog) closeDialog(); });
})();
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/dev/desxpert-admin/resources/views/admin/disbursements.blade.php ENDPATH**/ ?>