@extends('layouts.app')

@section('title', 'Cuentas por cobrar | Veltrix v2')
@section('page_title', 'Cuentas por cobrar')
@section('page_subtitle', 'Gestion operativa en tiempo real')
@section('page_icon', 'bx bx-wallet-alt')

@section('content')
@php
    $filters = $filters ?? [
        'cliente_id' => 0,
        'fecha_desde' => '',
        'fecha_hasta' => '',
        'estado' => 'todos',
    ];
    $customers = $customers ?? [];
    $accounts = $accounts ?? [];
    $payments = $payments ?? [];
    $summary = $summary ?? [
        'total_credito' => 0, 'total_abonado' => 0, 'total_saldo' => 0,
        'cuentas_pendientes' => 0, 'cuentas_parciales' => 0,
    ];
    $aging = $aging ?? [
        'saldo_0_30' => 0, 'saldo_31_60' => 0, 'saldo_61_90' => 0, 'saldo_91_mas' => 0,
        'cuentas_0_30' => 0, 'cuentas_31_60' => 0, 'cuentas_61_90' => 0, 'cuentas_91_mas' => 0,
    ];
@endphp

@if (session('status'))
    <div class="alert alert-success border-0 shadow-sm mb-3">{{ session('status') }}</div>
@endif
@if (session('error'))
    <div class="alert alert-danger border-0 shadow-sm mb-3">{{ session('error') }}</div>
@endif

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
        <div class="d-flex flex-wrap align-items-start justify-content-between gap-2 mb-3">
            <div>
                <h1 class="h6 mb-1">Filtros de cartera</h1>
                <p class="text-muted small mb-0">Refina resultados por cliente, fechas y estado. Exporta en un clic.</p>
            </div>
        </div>
        <form method="get" action="{{ route('cuentas-cobrar.index') }}" class="row g-2 align-items-end vx-receivables-filters">
            <div class="col-md-3">
                <label class="form-label">Cliente</label>
                <select name="cliente_id" class="form-select">
                    <option value="0">Todos</option>
                    @foreach ($customers as $customer)
                        <option value="{{ (int) $customer['id'] }}" @selected((int) ($filters['cliente_id'] ?? 0) === (int) $customer['id'])>
                            {{ $customer['nombre'] }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Fecha desde</label>
                <input type="date" class="form-control" name="fecha_desde" value="{{ (string) ($filters['fecha_desde'] ?? '') }}">
            </div>
            <div class="col-md-2">
                <label class="form-label">Fecha hasta</label>
                <input type="date" class="form-control" name="fecha_hasta" value="{{ (string) ($filters['fecha_hasta'] ?? '') }}">
            </div>
            <div class="col-md-2">
                <label class="form-label">Estado</label>
                <select name="estado" class="form-select">
                    <option value="todos" @selected(($filters['estado'] ?? 'todos') === 'todos')>Todos</option>
                    <option value="pendiente" @selected(($filters['estado'] ?? 'todos') === 'pendiente')>Pendiente</option>
                    <option value="parcial" @selected(($filters['estado'] ?? 'todos') === 'parcial')>Parcial</option>
                </select>
            </div>
            <div class="col-md-3 d-flex flex-wrap gap-2 justify-content-end">
                <button class="btn btn-primary" type="submit">
                    <i class="bx bx-filter-alt me-1"></i>Filtrar
                </button>
                <a class="btn btn-light" href="{{ route('cuentas-cobrar.index') }}">
                    <i class="bx bx-refresh me-1"></i>Limpiar
                </a>
            </div>
            <div class="col-12 d-flex flex-wrap gap-2 justify-content-end">
                <a class="btn btn-outline-success btn-sm" href="{{ $exportCsvUrl }}">
                    <i class="bx bx-file me-1"></i>CSV
                </a>
                <a class="btn btn-outline-success btn-sm" href="{{ $exportXlsxUrl }}">
                    <i class="bx bx-table me-1"></i>XLSX
                </a>
                <a class="btn btn-outline-danger btn-sm" href="{{ $exportPdfUrl }}">
                    <i class="bx bxs-file-pdf me-1"></i>PDF
                </a>
            </div>
        </form>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-3">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label text-muted small">Credito colocado</span>
                <h2 class="h5 mb-0">{{ money($summary['total_credito'] ?? 0) }}</h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label text-muted small">Total abonado</span>
                <h2 class="h5 mb-0 text-success">{{ money($summary['total_abonado'] ?? 0) }}</h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label text-muted small">Saldo por cobrar</span>
                <h2 class="h5 mb-0 text-danger">{{ money($summary['total_saldo'] ?? 0) }}</h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label text-muted small">Cuentas abiertas</span>
                <h2 class="h5 mb-0">{{ (int) ($summary['cuentas_pendientes'] ?? 0) + (int) ($summary['cuentas_parciales'] ?? 0) }}</h2>
                <small class="text-muted">
                    Pendientes: {{ (int) ($summary['cuentas_pendientes'] ?? 0) }} |
                    Parciales: {{ (int) ($summary['cuentas_parciales'] ?? 0) }}
                </small>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-3">
    @foreach ([
        ['label' => 'Vencimiento 0-30', 'saldo' => $aging['saldo_0_30'] ?? 0, 'cuentas' => $aging['cuentas_0_30'] ?? 0, 'danger' => false],
        ['label' => 'Vencimiento 31-60', 'saldo' => $aging['saldo_31_60'] ?? 0, 'cuentas' => $aging['cuentas_31_60'] ?? 0, 'danger' => false],
        ['label' => 'Vencimiento 61-90', 'saldo' => $aging['saldo_61_90'] ?? 0, 'cuentas' => $aging['cuentas_61_90'] ?? 0, 'danger' => false],
        ['label' => 'Vencimiento 91+', 'saldo' => $aging['saldo_91_mas'] ?? 0, 'cuentas' => $aging['cuentas_91_mas'] ?? 0, 'danger' => true],
    ] as $bucket)
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <span class="metric-label text-muted small">{{ $bucket['label'] }}</span>
                    <h3 class="h6 mb-1 {{ $bucket['danger'] ? 'text-danger' : '' }}">{{ money($bucket['saldo']) }}</h3>
                    <small class="text-muted">{{ (int) $bucket['cuentas'] }} cuenta(s)</small>
                </div>
            </div>
        </div>
    @endforeach
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
        <h2 class="h5 mb-3">Ventas con saldo pendiente</h2>
        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead>
                    <tr>
                        <th>Venta</th>
                        <th>Fecha</th>
                        <th>Cliente</th>
                        <th>Cajero</th>
                        <th>Total</th>
                        <th>Abonado</th>
                        <th>Saldo</th>
                        <th>Dias</th>
                        <th>Rango</th>
                        <th>Estado</th>
                        <th>Accion</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse ($accounts as $account)
                        <tr>
                            <td>#{{ (int) $account['id'] }}</td>
                            <td>{{ $account['fecha'] }}</td>
                            <td>{{ $account['cliente'] ?? 'Consumidor final' }}</td>
                            <td>{{ $account['cajero'] ?? '' }}</td>
                            <td>{{ money($account['total'] ?? 0) }}</td>
                            <td><span class="text-success fw-semibold">{{ money($account['pagado'] ?? 0) }}</span></td>
                            <td><span class="text-danger fw-semibold">{{ money($account['saldo'] ?? 0) }}</span></td>
                            <td>{{ (int) ($account['dias_cartera'] ?? 0) }}</td>
                            <td><span class="badge text-bg-light">{{ $account['rango_antiguedad'] ?? '0-30' }}</span></td>
                            <td>
                                @php $estadoCobro = (string) ($account['estado_cobro'] ?? 'pendiente'); @endphp
                                <span class="badge {{ $estadoCobro === 'parcial' ? 'text-bg-warning' : 'text-bg-danger' }}">
                                    {{ $estadoCobro }}
                                </span>
                            </td>
                            <td>
                                @if (has_permission('cuentas_cobrar.abonar'))
                                    <button class="btn btn-sm btn-outline-primary" type="button"
                                        data-bs-toggle="collapse"
                                        data-bs-target="#collectForm{{ (int) $account['id'] }}">
                                        Registrar abono
                                    </button>
                                @endif
                            </td>
                        </tr>
                        @if (has_permission('cuentas_cobrar.abonar'))
                            <tr>
                                <td colspan="11" class="bg-light p-0">
                                    <div class="collapse" id="collectForm{{ (int) $account['id'] }}">
                                        <form action="{{ route('cuentas-cobrar.collect', (int) $account['id']) }}" method="post" class="row g-2 p-3 m-0">
                                            @csrf
                                            <div class="col-md-2">
                                                <label class="form-label">Monto</label>
                                                <input type="number" step="0.01" min="0.01"
                                                    max="{{ (float) ($account['saldo'] ?? 0) }}"
                                                    class="form-control" name="monto"
                                                    value="{{ number_format((float) ($account['saldo'] ?? 0), 2, '.', '') }}"
                                                    required>
                                            </div>
                                            <div class="col-md-2">
                                                <label class="form-label">Metodo</label>
                                                <select class="form-select" name="metodo_pago" required>
                                                    @foreach (($paymentMethods ?? []) as $paymentMethod)
                                                        <option value="{{ $paymentMethod['codigo'] ?? 'efectivo' }}">
                                                            {{ $paymentMethod['nombre'] ?? 'Metodo' }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label">Referencia</label>
                                                <input class="form-control" name="referencia" placeholder="Comprobante, banco, etc.">
                                            </div>
                                            <div class="col-md-4 d-flex align-items-end">
                                                <button class="btn btn-primary w-100" type="submit">Guardar abono</button>
                                            </div>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @endif
                    @empty
                        <tr>
                            <td colspan="11" class="text-center text-muted py-4">
                                No hay cuentas por cobrar pendientes.
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <h2 class="h5 mb-3">Abonos recientes</h2>
        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead>
                    <tr>
                        <th>ID pago</th>
                        <th>Venta</th>
                        <th>Cliente</th>
                        <th>Fecha</th>
                        <th>Metodo</th>
                        <th>Referencia</th>
                        <th>Monto</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse ($payments as $payment)
                        <tr>
                            <td>{{ (int) $payment['id'] }}</td>
                            <td>#{{ (int) $payment['venta_id'] }}</td>
                            <td>{{ $payment['cliente'] ?? 'Consumidor final' }}</td>
                            <td>{{ $payment['fecha_pago'] ?? '' }}</td>
                            <td>{{ $payment['metodo_pago'] ?? '' }}</td>
                            <td>{{ $payment['referencia'] ?? '' }}</td>
                            <td class="text-success fw-semibold">{{ money($payment['monto'] ?? 0) }}</td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="7" class="text-center text-muted py-4">Sin abonos registrados.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>
@endsection
