<?php
    use App\Support\Format;
    use App\Services\PaymentManager;
    $record = $getRecord();
    $payments = $record->payments()->with('registeredBy')->orderByDesc('payment_date')->get();

    // "Recaudado" real = solo pagos efectivos. Excluye los anulados (voided) y los
    // asientos de reversión: NO representan dinero cobrado en este crédito (p. ej.
    // un pago mal registrado que se anuló o se trasladó a otro crédito).
    $validPayments = $payments->reject(fn ($p) => $p->voided || $p->payment_method === 'reversal');
    $totalPaid = $validPayments->sum('amount');
    $excludedCount = $payments->count() - $validPayments->count();

    $paymentManager = app(PaymentManager::class);

    // La anulación de pagos es exclusiva de administradores (admin / super_admin).
    // Supervisores y cobradores no ven el botón "Anular".
    $userCanVoidPayments = (bool) auth()->user()?->hasAnyRole(['super_admin', 'admin']);
?>

<style>
    .void-pay-btn {
        cursor: pointer;
        border: 1px solid rgb(220 38 38);
        color: rgb(220 38 38);
        background: transparent;
        padding: 0.15rem 0.6rem;
        border-radius: 0.375rem;
        font-size: 0.75rem;
        font-weight: 600;
        line-height: 1.2;
        white-space: nowrap;
        transition: background-color .15s, color .15s;
    }
    .void-pay-btn:hover { background: rgb(220 38 38); color: #fff; }
    .void-pay-btn:disabled { opacity: .5; cursor: wait; }
</style>

<div>
    
    <div class="stats-grid stats-grid-3">
        <div class="stat-card stat-card-success">
            <div class="stat-value stat-value-success"><?php echo e(Format::money($totalPaid)); ?></div>
            <div class="stat-label">Total Recaudado</div>
        </div>
        <div class="stat-card stat-card-default">
            <div class="stat-value"><?php echo e($validPayments->count()); ?></div>
            <div class="stat-label">Pagos Válidos</div>
        </div>
        <div class="stat-card stat-card-default">
            <div class="stat-value">
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($validPayments->isNotEmpty()): ?>
                    <?php echo e(Format::money($validPayments->avg('amount'))); ?>

                <?php else: ?>
                    -
                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            </div>
            <div class="stat-label">Promedio por Pago</div>
        </div>
    </div>

    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($excludedCount > 0): ?>
        <div style="margin: 0.625rem 0 0.75rem; padding: 0.5rem 0.75rem; border-left: 3px solid rgb(217 119 6); background: rgb(254 252 232); border-radius: 0.25rem; font-size: 0.8rem; color: rgb(146 64 14);">
            <strong><?php echo e($excludedCount); ?></strong> movimiento(s) anulado(s) o revertido(s) (en gris, tachados abajo).
            <strong>No</strong> suman al total recaudado.
        </div>
    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

    
    <div class="credit-table-container">
        <table class="credit-table">
            <thead>
                <tr>
                    <th>Ref.</th>
                    <th>Fecha</th>
                    <th class="text-right">Monto</th>
                    <th class="text-center">Método</th>
                    <th>Registrado por</th>
                    <th>Notas</th>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($userCanVoidPayments): ?>
                        <th class="text-center">Acciones</th>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </tr>
            </thead>
            <tbody>
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__empty_1 = true; $__currentLoopData = $payments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $payment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoopIteration(); ?><?php endif; ?>
                    <?php
                        $isVoided = (bool) $payment->voided;
                        $isReversal = $payment->payment_method === 'reversal';
                        $muted = $isVoided || $isReversal;

                        $methodLabel = match($payment->payment_method) {
                            'cash' => 'Efectivo',
                            'transfer' => 'Transferencia',
                            'nequi' => 'Nequi',
                            'daviplata' => 'Daviplata',
                            'bancolombia' => 'Bancolombia',
                            'card' => 'Tarjeta',
                            'reversal' => 'Reversión',
                            default => ucfirst($payment->payment_method ?? '-'),
                        };

                        $badgeClass = match(true) {
                            $isReversal => 'badge-gray',
                            $payment->payment_method === 'cash' => 'badge-success',
                            in_array($payment->payment_method, ['transfer', 'bancolombia'], true) => 'badge-info',
                            $payment->payment_method === 'nequi' => 'badge-purple',
                            $payment->payment_method === 'daviplata' => 'badge-danger',
                            $payment->payment_method === 'card' => 'badge-warning',
                            default => 'badge-gray',
                        };

                        // Para un pago anulado mostramos el motivo (clave para auditar):
                        // p. ej. "Error al registrar el pago, se traslada al crédito 87".
                        $note = $isVoided && $payment->void_reason
                            ? $payment->void_reason
                            : ($payment->notes ?? '-');

                        // Solo administradores, y solo pagos EFECTIVOS no bloqueados por
                        // reglas del sistema, pueden anularse. Fijamos la relación `credit`
                        // para evitar una consulta por fila dentro de canDeletePayment.
                        $canVoid = $userCanVoidPayments && ! $muted;
                        if ($canVoid) {
                            $payment->setRelation('credit', $record);
                            $canVoid = $paymentManager->canDeletePayment($payment);
                        }
                    ?>
                    <tr <?php if($muted): ?> style="opacity: 0.55;" <?php endif; ?>>
                        <td class="money" style="color: rgb(107 114 128);">#<?php echo e($payment->id); ?></td>
                        <td>
                            <div><?php echo e($payment->payment_date->format('d/m/Y')); ?></div>
                            <div style="font-size: 0.75rem; color: rgb(156 163 175);"><?php echo e($payment->payment_date->diffForHumans()); ?></div>
                        </td>
                        <td class="text-right money <?php if(! $muted): ?> money-success <?php endif; ?>"
                            style="font-weight: 700; <?php if($muted): ?> text-decoration: line-through; color: rgb(156 163 175); <?php endif; ?>">
                            <?php echo e(Format::money($payment->amount)); ?>

                        </td>
                        <td class="text-center">
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($isVoided): ?>
                                <span class="credit-badge badge-danger">Anulado</span>
                            <?php else: ?>
                                <span class="credit-badge <?php echo e($badgeClass); ?>"><?php echo e($methodLabel); ?></span>
                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                        </td>
                        <td style="color: rgb(107 114 128);">
                            <?php echo e($payment->registeredBy?->name ?? 'Sistema'); ?>

                        </td>
                        <td style="color: rgb(107 114 128); max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
                            title="<?php echo e($note); ?>">
                            <?php echo e($note); ?>

                        </td>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($userCanVoidPayments): ?>
                            <td class="text-center">
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($canVoid): ?>
                                    <button type="button"
                                        class="void-pay-btn"
                                        wire:click="mountAction('voidPayment', { payment: <?php echo e($payment->id); ?> })"
                                        wire:loading.attr="disabled"
                                        wire:target="mountAction"
                                        title="Anular este pago (genera una reversión con auditoría)">
                                        Anular
                                    </button>
                                <?php else: ?>
                                    <span style="color: rgb(209 213 219);">—</span>
                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                            </td>
                        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </tr>
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                    <tr>
                        <td colspan="<?php echo e($userCanVoidPayments ? 7 : 6); ?>" class="empty-state">
                            No hay pagos registrados
                        </td>
                    </tr>
                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            </tbody>
            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($validPayments->isNotEmpty()): ?>
            <tfoot>
                <tr>
                    <td colspan="2" class="text-right" style="font-size: 0.75rem; text-transform: uppercase;">Total recaudado:</td>
                    <td class="text-right money money-success"><?php echo e(Format::money($totalPaid)); ?></td>
                    <td colspan="<?php echo e($userCanVoidPayments ? 4 : 3); ?>"></td>
                </tr>
            </tfoot>
            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
        </table>
    </div>
</div>
<?php /**PATH /var/www/html/credifygo/resources/views/filament/infolists/components/payments-table.blade.php ENDPATH**/ ?>