{% extends 'base.html' %}
{% block content %}
<div class="page-toolbar">
  <div>
    <h1 class="h3 mb-1">Instituciones</h1>
    <p class="text-muted mb-0">Alta de clínicas, sanatorios, instituciones, equipos médicos o profesionales individuales. Cada institución conserva sus usuarios, pacientes, profesionales, turnos, chats y documentos aislados.</p>
  </div>
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#institutionModal"><i class="bi bi-plus-circle"></i> Nueva institución</button>
</div>

<div class="card table-panel">
  <div class="table-responsive wide-table">
    <table class="table align-middle mb-0">
      <thead><tr><th>Institución</th><th>CUIT / Habilitación</th><th>Contacto</th><th>Logo</th><th>Estado</th><th class="text-end">Acciones</th></tr></thead>
      <tbody>
      {% for item in institutions %}
      <tr>
        <td><strong>{{ item.name }}</strong><br><span class="small text-muted">{{ item.domicilio or 'Sin domicilio' }} · {{ item.ciudad or '' }} {{ item.provincia or '' }}</span><br><span class='badge text-bg-light border'>{{ item.branches|length }} sede(s)</span></td>
        <td>{{ item.cuit or '—' }}<br><span class="small text-muted">Hab. {{ item.nro_habilitacion or '—' }} · Exp. {{ item.expediente_autorizacion or '—' }}</span></td>
        <td>{{ item.email or '—' }}<br><span class="small text-muted">{{ item.telefono or '—' }} · Responsable: {{ item.responsable or '—' }}</span></td>
        <td>{% if item.logo_path %}<img src="{{ url_for('static', filename=item.logo_path) }}" style="max-height:42px;max-width:120px;object-fit:contain">{% else %}<span class="text-muted">Sin logo</span>{% endif %}</td>
        <td><span class="badge {% if item.active %}text-bg-success{% else %}text-bg-secondary{% endif %}">{{ 'Activa' if item.active else 'Inactiva' }}</span></td>
        <td class="text-end"><div class="d-flex gap-2 justify-content-end flex-wrap"><a class="btn btn-sm btn-outline-primary" href="{{ url_for('admin_institutions', edit=item.id) }}">Editar</a><form method="post" action="{{ url_for('admin_institution_toggle', institution_id=item.id) }}"><button class="btn btn-sm btn-outline-secondary">Activar / desactivar</button></form></div></td>
      </tr>
      {% else %}
      <tr><td colspan="6" class="text-center text-muted py-4">Todavía no hay instituciones cargadas.</td></tr>
      {% endfor %}
      </tbody>
    </table>
  </div>
</div>

<div class="modal fade" id="institutionModal" tabindex="-1">
  <div class="modal-dialog modal-xl modal-dialog-scrollable"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">{{ 'Editar institución' if edit_institution else 'Nueva institución' }}</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="post" enctype="multipart/form-data">
      <div class="modal-body"><div class="row g-4 modal-form-grid">
        {% if edit_institution %}<input type="hidden" name="institution_id" value="{{ edit_institution.id }}">{% endif %}
        <div class="col-12"><div class="section-card"><div class="section-title">Datos institucionales</div><div class="row g-3">
          <div class="col-md-6"><label class="form-label">Nombre</label><input class="form-control" name="name" value="{{ edit_institution.name if edit_institution else '' }}" required></div>
          <div class="col-md-3"><label class="form-label">CUIT</label><input class="form-control" name="cuit" value="{{ edit_institution.cuit if edit_institution else '' }}"></div>
          <div class="col-md-3"><label class="form-label">Situación jurídica</label><input class="form-control" name="situacion_juridica" value="{{ edit_institution.situacion_juridica if edit_institution else '' }}"></div>
          <div class="col-md-6"><label class="form-label">Domicilio</label><input class="form-control" name="domicilio" value="{{ edit_institution.domicilio if edit_institution else '' }}"></div>
          <div class="col-md-3"><label class="form-label">Ciudad</label><input class="form-control" name="ciudad" value="{{ edit_institution.ciudad if edit_institution else '' }}"></div>
          <div class="col-md-3"><label class="form-label">Provincia</label><input class="form-control" name="provincia" value="{{ edit_institution.provincia if edit_institution else '' }}"></div>
          <div class="col-md-4"><label class="form-label">N° habilitación</label><input class="form-control" name="nro_habilitacion" value="{{ edit_institution.nro_habilitacion if edit_institution else '' }}"></div>
          <div class="col-md-4"><label class="form-label">Expediente autorización</label><input class="form-control" name="expediente_autorizacion" value="{{ edit_institution.expediente_autorizacion if edit_institution else '' }}"></div>
          <div class="col-md-4"><label class="form-label">Logo institucional</label><input class="form-control" type="file" name="logo" accept="image/*"><div class="form-text">Saldrá junto al logo de la plataforma en documentos digitales.</div></div>
          <div class="col-md-4"><label class="form-label">Mail</label><input class="form-control" type="email" name="email" value="{{ edit_institution.email if edit_institution else '' }}"></div>
          <div class="col-md-4"><label class="form-label">Teléfono</label><input class="form-control" name="telefono" value="{{ edit_institution.telefono if edit_institution else '' }}"></div>
          <div class="col-md-4"><label class="form-label">Responsable</label><input class="form-control" name="responsable" value="{{ edit_institution.responsable if edit_institution else '' }}"></div>
          <div class="col-md-4"><label class="form-label">Teléfono responsable</label><input class="form-control" name="telefono_responsable" value="{{ edit_institution.telefono_responsable if edit_institution else '' }}"></div>
          <div class="col-md-4"><div class="form-check mt-4"><input class="form-check-input" type="checkbox" name="active" id="inst_active" {% if not edit_institution or edit_institution.active %}checked{% endif %}><label class="form-check-label" for="inst_active">Institución activa</label></div></div>
        </div></div></div>
        <div class="col-12"><div class="section-card"><div class="d-flex align-items-center justify-content-between gap-2 mb-2"><div class="section-title mb-0">Sedes de atención</div><button type="button" class="btn btn-sm btn-outline-primary" id="addBranchRow"><i class="bi bi-plus-circle"></i> Agregar sede</button></div>
          <p class="text-muted small mb-3">Estas sedes se mostrarán en la solicitud pública de turnos y en el Chatbot IA. Si la institución tiene más de una sede, el paciente podrá elegir provincia, ciudad y sede.</p>
          <div id="branchesBox" class="d-grid gap-3">
            {% set branch_items = edit_institution.branches if edit_institution else [] %}
            {% for branch in branch_items %}
            <div class="branch-row border rounded-4 p-3 bg-light-subtle">
              <input type="hidden" name="branch_id[]" value="{{ branch.id }}">
              <div class="row g-2 align-items-end">
                <div class="col-md-3"><label class="form-label">Nombre sede</label><input class="form-control" name="branch_name[]" value="{{ branch.name }}" placeholder="Sede Centro"></div>
                <div class="col-md-3"><label class="form-label">Dirección</label><input class="form-control" name="branch_address[]" value="{{ branch.address or '' }}"></div>
                <div class="col-md-2"><label class="form-label">Ciudad</label><input class="form-control" name="branch_city[]" value="{{ branch.city or '' }}"></div>
                <div class="col-md-2"><label class="form-label">Provincia</label><input class="form-control" name="branch_province[]" value="{{ branch.province or '' }}"></div>
                <div class="col-md-2"><label class="form-label">Teléfono</label><input class="form-control" name="branch_phone[]" value="{{ branch.phone or '' }}"></div>
                <div class="col-md-4"><label class="form-label">Email sede</label><input class="form-control" name="branch_email[]" value="{{ branch.email or '' }}"></div>
                <div class="col-md-3"><div class="form-check mt-4"><input class="form-check-input" type="checkbox" name="branch_active[]" value="{{ loop.index0 }}" {% if branch.active %}checked{% endif %}><label class="form-check-label">Sede activa</label></div></div>
                <div class="col-md-3 text-md-end"><button type="button" class="btn btn-outline-danger btn-sm remove-branch-row">Quitar de la pantalla</button></div>
              </div>
            </div>
            {% endfor %}
          </div>
          <template id="branchRowTemplate">
            <div class="branch-row border rounded-4 p-3 bg-light-subtle">
              <input type="hidden" name="branch_id[]" value="">
              <div class="row g-2 align-items-end">
                <div class="col-md-3"><label class="form-label">Nombre sede</label><input class="form-control" name="branch_name[]" placeholder="Sede Centro"></div>
                <div class="col-md-3"><label class="form-label">Dirección</label><input class="form-control" name="branch_address[]"></div>
                <div class="col-md-2"><label class="form-label">Ciudad</label><input class="form-control" name="branch_city[]"></div>
                <div class="col-md-2"><label class="form-label">Provincia</label><input class="form-control" name="branch_province[]"></div>
                <div class="col-md-2"><label class="form-label">Teléfono</label><input class="form-control" name="branch_phone[]"></div>
                <div class="col-md-4"><label class="form-label">Email sede</label><input class="form-control" name="branch_email[]"></div>
                <div class="col-md-3"><div class="form-check mt-4"><input class="form-check-input branch-active-check" type="checkbox" name="branch_active[]" checked><label class="form-check-label">Sede activa</label></div></div>
                <div class="col-md-3 text-md-end"><button type="button" class="btn btn-outline-danger btn-sm remove-branch-row">Quitar</button></div>
              </div>
            </div>
          </template>
        </div></div>
        <div class="col-12"><div class="section-card"><div class="section-title">Secretario principal opcional</div><div class="row g-3">
          <div class="col-md-4"><label class="form-label">Nombre secretario</label><input class="form-control" name="secretary_name"></div>
          <div class="col-md-4"><label class="form-label">Email secretario</label><input class="form-control" type="email" name="secretary_email"></div>
          <div class="col-md-4"><label class="form-label">Clave provisoria</label><input class="form-control" name="secretary_password" placeholder="Cambio1234"></div>
        </div></div></div>
      </div></div>
      <div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancelar</button><button class="btn btn-primary">Guardar institución</button></div>
    </form>
  </div></div>
</div>
{% endblock %}
{% block scripts %}{{ super() }}
<script>
document.addEventListener('DOMContentLoaded', function(){
  const box = document.getElementById('branchesBox');
  const tpl = document.getElementById('branchRowTemplate');
  function renumberBranchChecks(){
    box?.querySelectorAll('.branch-row').forEach((row, idx) => {
      const chk = row.querySelector('input[name="branch_active[]"]');
      if(chk) chk.value = String(idx);
    });
  }
  document.getElementById('addBranchRow')?.addEventListener('click', () => {
    if(!box || !tpl) return;
    box.appendChild(tpl.content.cloneNode(true));
    renumberBranchChecks();
  });
  box?.addEventListener('click', (ev) => {
    if(ev.target.closest('.remove-branch-row')){
      ev.target.closest('.branch-row')?.remove();
      renumberBranchChecks();
    }
  });
  if(box && box.children.length === 0){ document.getElementById('addBranchRow')?.click(); }
  renumberBranchChecks();
});
</script>
{% if edit_institution %}<script>document.addEventListener('DOMContentLoaded',function(){ new bootstrap.Modal(document.getElementById('institutionModal')).show(); });</script>{% endif %}{% endblock %}
