{% extends "base.html" %}
{% block title %}Modelo 303{% endblock %}
{% block page_title %}Modelo 303 — IVA trimestral{% endblock %}

{% block topbar_actions %}
<a href="{{ url_for('fiscal.index') }}" class="btn btn-outline-secondary btn-sm">
  <i class="bi bi-arrow-left me-1"></i>Volver al calendario
</a>
{% endblock %}

{% block content %}

<!-- Selector -->
<div class="card mb-4 border-0 shadow-sm">
  <div class="card-body py-3">
    <form method="get" class="d-flex align-items-center gap-3 flex-wrap">
      <div class="d-flex align-items-center gap-2">
        <label class="fw-semibold text-muted">Ejercicio</label>
        <select name="ejercicio" class="form-select form-select-sm" style="width:110px">
          {% for a in años %}<option {{ 'selected' if a==año }}>{{ a }}</option>{% endfor %}
        </select>
      </div>
      <div class="d-flex align-items-center gap-2">
        <label class="fw-semibold text-muted">Trimestre</label>
        <select name="trimestre" class="form-select form-select-sm" style="width:90px">
          {% for t in trimestres %}<option {{ 'selected' if t==trim }}>{{ t }}</option>{% endfor %}
        </select>
      </div>
      <button type="submit" class="btn btn-primary btn-sm">
        <i class="bi bi-calculator me-1"></i>Calcular
      </button>
    </form>
  </div>
</div>

<!-- Estado guardado -->
{% if guardado %}
<div class="alert {% if guardado.estado=='presentado' %}alert-success{% else %}alert-warning{% endif %} d-flex align-items-center gap-3 mb-4">
  <i class="bi {% if guardado.estado=='presentado' %}bi-check-circle-fill{% else %}bi-pencil-square{% endif %} fs-4 flex-shrink-0"></i>
  <div>
    <strong>{{ 'Modelo presentado' if guardado.estado=='presentado' else 'Borrador guardado' }}</strong>
    &mdash; Resultado: {{ "%.2f"|format(guardado.resultado) }} €
    {% if guardado.fecha_presentacion %}&nbsp;· Presentado el {{ guardado.fecha_presentacion }}{% endif %}
    {% if guardado.notas %}<br><small class="text-muted">{{ guardado.notas }}</small>{% endif %}
  </div>
</div>
{% endif %}

<div class="row g-4">

  <!-- IVA Devengado -->
  <div class="col-lg-6">
    <div class="card h-100 border-0 shadow-sm">
      <div class="card-header border-0"
           style="background:linear-gradient(135deg,#eef3ff,#e0e7ff)">
        <i class="bi bi-arrow-up-circle me-2 text-primary"></i>
        <span class="fw-semibold text-primary">IVA Devengado (facturas emitidas)</span>
      </div>
      <div class="card-body p-0">
        <table class="table mb-0" style="font-size:.875rem">
          <thead>
            <tr>
              <th>Tipo IVA</th>
              <th class="text-end">Base imp.</th>
              <th class="text-end">Cuota</th>
              <th class="text-end text-danger">–Rect.</th>
              <th class="text-end fw-bold">Neto</th>
            </tr>
          </thead>
          <tbody>
            {% for r in calc.dev_neto %}
            <tr>
              <td><span class="badge bg-primary bg-opacity-10 text-primary">{{ r.iva_pct }}%</span></td>
              <td class="text-end">{{ "%.2f"|format(r.base) }} €</td>
              <td class="text-end">{{ "%.2f"|format(r.cuota) }} €</td>
              <td class="text-end text-danger">{{ "%.2f"|format(r.rect_cuota) }} €</td>
              <td class="text-end fw-semibold">{{ "%.2f"|format(r.cuota_neta) }} €</td>
            </tr>
            {% else %}
            <tr><td colspan="5" class="text-center text-muted py-3">Sin facturas emitidas en este período</td></tr>
            {% endfor %}
          </tbody>
          <tfoot class="table-light fw-bold">
            <tr>
              <td>TOTAL</td>
              <td class="text-end">{{ "%.2f"|format(calc.total_dev_base) }} €</td>
              <td class="text-end"></td>
              <td class="text-end text-danger"></td>
              <td class="text-end text-primary">{{ "%.2f"|format(calc.total_dev_cuota) }} €</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>

  <!-- IVA Soportado -->
  <div class="col-lg-6">
    <div class="card h-100 border-0 shadow-sm">
      <div class="card-header border-0"
           style="background:linear-gradient(135deg,#fff5f5,#fee2e2)">
        <i class="bi bi-arrow-down-circle me-2 text-danger"></i>
        <span class="fw-semibold text-danger">IVA Soportado (gastos deducibles)</span>
      </div>
      <div class="card-body p-0">
        <table class="table mb-0" style="font-size:.875rem">
          <thead>
            <tr>
              <th>Tipo IVA</th>
              <th class="text-end">Base imp.</th>
              <th class="text-end fw-bold">Cuota</th>
            </tr>
          </thead>
          <tbody>
            {% for r in calc.soportado %}
            <tr>
              <td><span class="badge bg-danger bg-opacity-10 text-danger">{{ r.iva_pct }}%</span></td>
              <td class="text-end">{{ "%.2f"|format(r.base) }} €</td>
              <td class="text-end fw-semibold">{{ "%.2f"|format(r.cuota) }} €</td>
            </tr>
            {% else %}
            <tr><td colspan="3" class="text-center text-muted py-3">Sin gastos deducibles en este período</td></tr>
            {% endfor %}
          </tbody>
          <tfoot class="table-light fw-bold">
            <tr>
              <td>TOTAL</td>
              <td class="text-end">{{ "%.2f"|format(calc.total_sop_base) }} €</td>
              <td class="text-end text-danger">{{ "%.2f"|format(calc.total_sop_cuota) }} €</td>
            </tr>
          </tfoot>
        </table>
      </div>
      {% if calc.sop_fr or calc.sop_tg %}
      <div class="card-footer border-0 bg-transparent pt-0">
        <div class="d-flex gap-3" style="font-size:.78rem;color:#64748b">
          <span><i class="bi bi-file-earmark-text me-1"></i>Facturas recibidas: <b>{{ "%.2f"|format(calc.sop_fr|sum(attribute='cuota') if calc.sop_fr else 0) }} €</b></span>
          <span><i class="bi bi-receipt me-1"></i>Tickets: <b>{{ "%.2f"|format(calc.sop_tg|sum(attribute='cuota') if calc.sop_tg else 0) }} €</b></span>
        </div>
      </div>
      {% endif %}
    </div>
  </div>

</div>

<!-- Resultado -->
<div class="card mt-4 border-0 shadow"
     style="background:linear-gradient(135deg,{% if calc.resultado >= 0 %}#1e40af,#1d4ed8{% else %}#15803d,#16a34a{% endif %})">
  <div class="card-body p-4">
    <div class="row align-items-center g-3">
      <div class="col-md-6 text-white">
        <div class="small opacity-75 mb-1">Período: {{ calc.fi }} → {{ calc.ff }}</div>
        <h5 class="mb-2 fw-bold">Resultado Modelo 303 — {{ trim }}/{{ año }}</h5>
        <div class="d-flex gap-4 opacity-90" style="font-size:.875rem">
          <div>IVA devengado: <b>{{ "%.2f"|format(calc.total_dev_cuota) }} €</b></div>
          <div>IVA soportado: <b>{{ "%.2f"|format(calc.total_sop_cuota) }} €</b></div>
        </div>
      </div>
      <div class="col-md-3 text-center text-white">
        <div class="opacity-75 small mb-1">
          {% if calc.resultado >= 0 %}A ingresar{% else %}A compensar / devolver{% endif %}
        </div>
        <div class="display-5 fw-bold">{{ "%.2f"|format(calc.resultado|abs) }} €</div>
      </div>
      <div class="col-md-3 d-flex justify-content-end gap-2 flex-wrap">
        <a href="{{ url_for('fiscal.exportar_303', ejercicio=año, trimestre=trim) }}"
           class="btn btn-outline-light btn-sm">
          <i class="bi bi-file-earmark-excel me-1"></i>Exportar Excel
        </a>
        <button type="button" class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#modalGuardar">
          <i class="bi bi-floppy me-1"></i>Guardar
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Modal guardar -->
<div class="modal fade" id="modalGuardar" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <form method="post" action="{{ url_for('fiscal.guardar_303') }}">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title"><i class="bi bi-floppy me-2"></i>Guardar Modelo 303</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="ejercicio" value="{{ año }}">
          <input type="hidden" name="trimestre" value="{{ trim }}">
          <div class="mb-3">
            <label class="form-label fw-semibold">Estado</label>
            <div class="d-flex gap-3">
              <div class="form-check">
                <input class="form-check-input" type="radio" name="estado" value="borrador"
                       id="rb" {{ 'checked' if not guardado or guardado.estado=='borrador' }}>
                <label class="form-check-label" for="rb">Borrador</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="estado" value="presentado"
                       id="rp" {{ 'checked' if guardado and guardado.estado=='presentado' }}>
                <label class="form-check-label" for="rp">Presentado</label>
              </div>
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label fw-semibold">Notas (opcional)</label>
            <textarea class="form-control" name="notas" rows="2" placeholder="Referencia AEAT, observaciones...">{{ guardado.notas if guardado and guardado.notas }}</textarea>
          </div>
          <div class="alert alert-info py-2 mb-0" style="font-size:.85rem">
            <i class="bi bi-info-circle me-1"></i>
            Resultado calculado: <b>{{ "%.2f"|format(calc.resultado) }} €</b>
            {% if calc.resultado >= 0 %}&nbsp;(a ingresar){% else %}&nbsp;(a compensar){% endif %}
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-primary btn-sm">
            <i class="bi bi-check2 me-1"></i>Guardar
          </button>
        </div>
      </div>
    </form>
  </div>
</div>

{% endblock %}
