@extends('layouts.app')

@section('content')
<div class="bg-body-light d-print-none">
    <div class="content content-full">
        <div class="d-flex flex-column flex-sm-row justify-content-sm-between align-items-sm-center py-2">
            <div class="flex-grow-1">
                <h1 class="h3 fw-bold mb-2">
                    <i class="fa fa-file-invoice-dollar text-info me-2"></i>Extracto de Cuenta
                </h1>
                <h2 class="fs-base lh-base fw-medium text-muted mb-0">
                    Historial consolidado del cliente: <span class="text-dark fw-bold">{{ $cliente->nombre }}</span>
                </h2>
            </div>
            <div class="flex-shrink-0 mt-3 mt-sm-0 ms-sm-3">
                <a href="{{ route('extractos.index') }}" class="btn btn-alt-secondary">
                    <i class="fa fa-search me-1"></i> Nueva Búsqueda
                </a>
                <a href="{{ route('extractos.pdf', $idcliente) }}" target="_blank" class="btn btn-alt-info">
                    <i class="fa fa-print me-1"></i> Generar PDF
                </a>
            </div>
        </div>
    </div>
</div>

<div class="content">
    {{-- Info del Cliente --}}
    <div class="block block-rounded mb-4">
        <div class="block-content block-content-full bg-info text-white">
            <div class="row items-push">
                <div class="col-md-4">
                    <div class="fs-xs text-uppercase fw-bold opacity-75">Código Cliente</div>
                    <div class="fs-lg fw-bold">#{{ $idcliente }}</div>
                </div>
                <div class="col-md-4 border-start-md">
                    <div class="fs-xs text-uppercase fw-bold opacity-75">Documento de Identidad</div>
                    <div class="fs-lg fw-bold">{{ $cliente->ci }}</div>
                </div>
                <div class="col-md-4 border-start-md">
                    <div class="fs-xs text-uppercase fw-bold opacity-75">Resumen de Cartera</div>
                    <div class="fs-lg fw-bold">{{ $totalContratos }} Contrato(s)</div>
                </div>
            </div>
        </div>
        @if($idcontrato)
        <div class="block-content py-2 bg-body-light border-bottom">
            <div class="alert alert-info py-1 px-3 mb-0 d-flex justify-content-between align-items-center fs-sm">
                <span><i class="fa fa-filter me-1"></i> Filtrando solo Contrato <strong>#{{ $idcontrato }}</strong></span>
                <a href="{{ route('extractos.show', $idcliente) }}" class="btn btn-sm btn-info py-0">Ver todo</a>
            </div>
        </div>
        @endif
    </div>

    {{-- ── Bloque por cada contrato ─────────────────────────────────────── --}}
    @foreach($bloques as $bloque)
    @php
      $contrato = $bloque['contrato'];
      $anulado  = $bloque['anulado'];
    @endphp

    <div class="block block-rounded block-bordered {{ $anulado ? 'opacity-50 border-danger' : '' }}">
        <div class="block-header {{ $anulado ? 'bg-danger-light' : 'bg-primary-dark' }} py-2">
            <h3 class="block-title text-white fs-sm fw-bold">
                <i class="fa {{ $anulado ? 'fa-ban' : 'fa-file-signature' }} me-2"></i>
                CONTRATO #{{ $bloque['idcontrato'] }} — {{ $anulado ? 'ANULADO' : 'VIGENTE' }}
                @if($bloque['lote'])
                    <span class="ms-3 fw-normal opacity-75">
                        {{ $bloque['urb']->nombre ?? '' }} | Mzno: {{ $bloque['lote']->manzano }} | Lote: {{ $bloque['lote']->nombre }}
                    </span>
                @endif
            </h3>
            <div class="block-options">
                <a href="{{ route('contratos.show', $bloque['idcontrato']) }}" class="btn btn-sm btn-alt-secondary py-0">
                    Ir a Ficha
                </a>
            </div>
        </div>

        <div class="block-content p-0">
            <div class="table-responsive">
                <table class="table table-vcenter table-sm table-striped mb-0" style="font-size: 0.78rem;">
                    <thead class="bg-body-dark">
                        <tr class="text-uppercase">
                            <th class="text-center" style="width: 85px;">Fecha</th>
                            <th>Concepto / Glosa</th>
                            <th class="text-center" title="Vendedor/Cobrador">V/C</th>
                            <th class="text-center" style="width: 60px;">Cuo.</th>
                            <th class="text-center">N° Recibo</th>
                            <th class="text-end" style="width: 100px;">Cargo $us</th>
                            <th class="text-end" style="width: 100px;">Abono $us</th>
                            <th class="text-end" style="width: 110px;">Saldo $us</th>
                        </tr>
                    </thead>
                    <tbody>
                        {{-- Unificamos las filas en una sola pasada para mejor orden --}}
                        @php 
                            $todasLasFilas = collect($bloque['filas_cargo'])->merge($bloque['filas_pago'])->sortBy('fecha_vencimiento_real'); 
                        @endphp

                        @foreach($todasLasFilas as $fila)
                            @php
                                $esCargo = in_array($fila->tipmov, [1, 5]);
                                $esAbono = in_array($fila->tipmov, [2, 6]);
                                $pagada  = ($fila->cargo > 0 && $fila->cargo == $fila->abono);
                            @endphp
                            <tr class="{{ $pagada ? 'table-success opacity-75' : '' }} {{ $esAbono && !$anulado ? 'table-warning text-dark fw-semibold' : '' }}">
                                <td class="text-center text-muted">
                                    {{ $fila->tipmov == 1 || $fila->tipmov == 5
                                        ? \App\Helpers\FechaHelper::bdToLocal($fila->fechaven)
                                        : \App\Helpers\FechaHelper::bdToLocal($fila->fecha) }}
                                </td>
                                <td>
                                    @if($fila->tipmov == 5 || $fila->tipmov == 6) <i class="fa fa-sliders-h text-warning me-1"></i> @endif
                                    {{ $anulado ? 'ANULADO' : $fila->tip }}
                                </td>
                                <td class="text-center text-muted">
                                    {{ ($fila->idvendedor ?: '') . '/' . ($fila->idcobrador ?: '') }}
                                </td>
                                <td class="text-center">
                                    {{ $fila->numcuo ?: '—' }}
                                </td>
                                <td class="text-center">
                                    @if($esAbono) <span class="badge bg-white text-dark border shadow-sm">{{ $fila->numrec ?: $fila->id }}</span> @endif
                                </td>
                                <td class="text-end">
                                    {{ $esCargo ? number_format($fila->cargo, 2) : '' }}
                                </td>
                                <td class="text-end">
                                    {{ $esAbono ? number_format($fila->cargo, 2) : '' }}
                                </td>
                                <td class="text-end fw-bold {{ $fila->saldo_acumulado > 0 ? 'text-danger' : 'text-success' }}">
                                    {{ number_format($fila->saldo_acumulado, 2) }}
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                    <tfoot class="bg-body-light fw-bold text-dark">
                        <tr>
                            <td colspan="5" class="text-end text-uppercase fs-xs">Subtotales Contrato #{{ $bloque['idcontrato'] }}</td>
                            <td class="text-end">{{ number_format($bloque['sumacargo'], 2) }}</td>
                            <td class="text-end">{{ number_format($bloque['sumaabono'], 2) }}</td>
                            <td class="text-end {{ $bloque['saldo'] > 0 ? 'text-danger' : 'text-success' }}">
                                {{ number_format($bloque['saldo'], 2) }}
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

    {{-- Totales generales al final del último contrato vigente --}}
    @if($bloque['es_ultimo_vigente'])
      <div class="block block-rounded block-bordered border-dark overflow-hidden shadow">
        <div class="block-content block-content-full bg-dark text-white p-2">
          <div class="row text-end">
              <div class="col-8 col-md-9 text-uppercase fs-sm fw-bold pt-1">Total General Cartera Cliente $us</div>
              <div class="col-4 col-md-3">
                  <span class="fs-lg fw-bold {{ $sumaSaldoTotal > 0 ? 'text-warning' : 'text-success' }}">
                      {{ number_format($sumaSaldoTotal, 2) }}
                  </span>
              </div>
          </div>
        </div>
      </div>
    @endif
    @endforeach

    @if(empty($bloques))
        <div class="block block-rounded bg-body-light text-center py-5">
            <i class="fa fa-info-circle fa-2x text-muted mb-3"></i>
            <p>No existen extractos registrados para este cliente.</p>
        </div>
    @endif
</div>
@endsection