{% extends 'base.html' %}
{% block content %}
<div class="page-toolbar">
  <div>
    <h1 class="h3 mb-1">Mi facturación SaaS</h1>
    <p class="text-muted mb-0">Consulta de liquidaciones, deuda y pagos de la institución.</p>
  </div>
  {% if current_user.role in ['admin','accounting'] and institutions %}
  <form class="d-flex gap-2" method="get">
    <select class="form-select searchable-select" name="institution_id">
      {% for inst in institutions %}<option value="{{ inst.id }}" {% if institution.id==inst.id %}selected{% endif %}>{{ inst.name }}</option>{% endfor %}
    </select>
    <button class="btn btn-outline-primary">Ver</button>
  </form>
  {% endif %}
</div>

<div class="section-card mb-3">
  <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
    <div>
      <h5 class="mb-1">{{ institution.name }}</h5>
      <div class="text-muted small">CUIT: {{ institution.cuit or '—' }} · Responsable: {{ institution.responsable or '—' }}</div>
    </div>
    {% if institution.logo_path %}<img src="{{ url_for('static', filename=institution.logo_path) }}" alt="Logo" style="max-height:52px;max-width:160px;object-fit:contain">{% endif %}
  </div>
</div>

<div class="row g-3 mb-3">
  <div class="col-md-4"><div class="stat-card"><div class="stat-label">Facturado</div><div class="stat-value">$ {{ '%.2f'|format(total_billed) }}</div></div></div>
  <div class="col-md-4"><div class="stat-card"><div class="stat-label">Pagado</div><div class="stat-value">$ {{ '%.2f'|format(total_paid) }}</div></div></div>
  <div class="col-md-4"><div class="stat-card"><div class="stat-label">Deuda pendiente</div><div class="stat-value">$ {{ '%.2f'|format(total_debt) }}</div></div></div>
</div>

<div class="card table-panel mb-3">
  <div class="card-header d-flex justify-content-between align-items-center"><strong>Liquidaciones</strong><span class="text-muted small">{{ invoices|length }} registros</span></div>
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead><tr><th>Período</th><th>Emisión</th><th>Vencimiento</th><th>Total</th><th>Pagado</th><th>Deuda</th><th>Estado</th><th>Acciones</th></tr></thead>
      <tbody>
      {% for i in invoices %}
      <tr class="{% if i.status=='anulada' %}table-light text-muted{% endif %}">
        <td>{{ i.period }}</td>
        <td>{{ i.issue_date.strftime('%d/%m/%Y') if i.issue_date else '—' }}</td>
        <td>{{ i.due_date.strftime('%d/%m/%Y') if i.due_date else '—' }}</td>
        <td>$ {{ '%.2f'|format(i.total_amount or 0) }}</td>
        <td>$ {{ '%.2f'|format(i.paid_amount or 0) }}</td>
        <td>$ {{ '%.2f'|format(i.debt_amount) }}</td>
        <td><span class="badge {% if i.status=='pagada' %}text-bg-success{% elif i.status=='parcial' %}text-bg-warning{% elif i.status=='anulada' %}text-bg-secondary{% else %}text-bg-danger{% endif %}">{{ i.status }}</span></td>
        <td>
          <div class="d-flex flex-wrap gap-1">
            <a class="btn btn-sm btn-outline-danger" href="{{ url_for('institution_invoice_receipt_pdf', invoice_id=i.id) }}"><i class="bi bi-file-earmark-pdf"></i> PDF</a>
            {% if i.status in ['pendiente','parcial'] and i.debt_amount > 0 %}
              {% if i.mercadopago_init_point or i.mercadopago_sandbox_init_point %}
                <a class="btn btn-sm btn-primary" href="{{ url_for('institution_billing_mp_pay', invoice_id=i.id) }}" target="_blank"><i class="bi bi-credit-card"></i> Pagar</a>
              {% else %}
                <a class="btn btn-sm btn-outline-primary" href="{{ url_for('institution_billing_mp_pay', invoice_id=i.id) }}"><i class="bi bi-link-45deg"></i> Generar pago</a>
              {% endif %}
            {% endif %}
          </div>
          {% if i.mercadopago_status %}<div class="small text-muted mt-1">Mercado Pago: {{ i.mercadopago_status }} {{ i.mercadopago_status_detail or '' }}</div>{% endif %}
        </td>
      </tr>
      {% else %}<tr><td colspan="8" class="text-center text-muted py-4">Todavía no hay liquidaciones para esta institución.</td></tr>{% endfor %}
      </tbody>
    </table>
  </div>
</div>

<div class="card table-panel">
  <div class="card-header"><strong>Pagos registrados</strong></div>
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead><tr><th>Fecha</th><th>Período</th><th>Método</th><th>Importe</th><th>Referencia</th><th>Estado</th></tr></thead>
      <tbody>{% for p in payments %}<tr><td>{{ p.payment_date.strftime('%d/%m/%Y') if p.payment_date else '—' }}</td><td>{{ p.invoice.period }}</td><td>{{ p.method }}</td><td>$ {{ '%.2f'|format(p.amount or 0) }}</td><td>{{ p.reference or p.mercadopago_payment_id or '—' }}</td><td>{{ p.status or p.mercadopago_status or 'registrado' }}</td></tr>{% else %}<tr><td colspan="6" class="text-center text-muted py-4">Sin pagos registrados.</td></tr>{% endfor %}</tbody>
    </table>
  </div>
</div>
{% endblock %}
