<?php
if (!isUserLoggedIn()) { header('Location: ' . BASE_URL . 'login.php'); exit; }
requireRole('admin');
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>EPS — <?= htmlspecialchars($_cfg['empresa_nombre'] ?? 'ERP') ?></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="<?= BASE_URL ?>assets/css/styles.css?v=15" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
.eps-table { width:100%; border-collapse:collapse; font-size:.9rem; }
.eps-table th { background:#f8fafc; font-weight:700; font-size:.75rem; text-transform:uppercase;
                letter-spacing:.06em; color:#64748b; padding:.6rem 1rem; border-bottom:2px solid #e2e8f0; }
.eps-table td { padding:.65rem 1rem; border-bottom:1px solid #f1f5f9; vertical-align:middle; }
.eps-table tr:hover td { background:#f8fafc; }
.badge-activa   { background:#dcfce7; color:#166534; font-size:.7rem; font-weight:700;
                  padding:2px 8px; border-radius:99px; }
.badge-inactiva { background:#f1f5f9; color:#94a3b8; font-size:.7rem; font-weight:700;
                  padding:2px 8px; border-radius:99px; }
</style>
</head>
<body>
<?php include APP_ROOT . '/partials/navbar.php'; ?>

<div class="container-fluid py-4" style="max-width:720px">
    <div class="d-flex align-items-center justify-content-between mb-3">
        <h5 class="mb-0"><i class="fas fa-hospital me-2 text-primary"></i>EPS / Aseguradoras</h5>
        <button class="btn btn-primary btn-sm" onclick="abrirModal()">
            <i class="fas fa-plus me-1"></i>Nueva EPS
        </button>
    </div>

    <div class="card shadow-sm">
        <div class="card-body p-0">
            <table class="eps-table" id="tbl-eps">
                <thead>
                    <tr>
                        <th>Nombre</th>
                        <th style="width:90px">Estado</th>
                        <th style="width:110px">Acciones</th>
                    </tr>
                </thead>
                <tbody id="tbody-eps">
                    <tr><td colspan="3" class="text-muted text-center py-3">Cargando…</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="modal-eps" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title" id="modal-eps-titulo">Nueva EPS</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="eps-id">
                <div class="mb-3">
                    <label class="form-label small fw-semibold">Nombre <span class="text-danger">*</span></label>
                    <input type="text" id="eps-nombre" class="form-control" maxlength="120"
                           placeholder="Ej: Nueva EPS, Sanitas, Sura…">
                </div>
                <div id="eps-error" class="text-danger small d-none"></div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancelar</button>
                <button class="btn btn-primary btn-sm" onclick="guardarEps()">
                    <i class="fas fa-save me-1"></i>Guardar
                </button>
            </div>
        </div>
    </div>
</div>

<script>
const API_EPS = '<?= BASE_URL ?>api/lab/eps.php';
let _modal;

async function cargarEps() {
    const r = await fetch(API_EPS + '?action=list');
    const j = await r.json();
    const tbody = document.getElementById('tbody-eps');
    if (!j.ok || !j.eps.length) {
        tbody.innerHTML = '<tr><td colspan="3" class="text-muted text-center py-3">Sin registros</td></tr>';
        return;
    }
    tbody.innerHTML = j.eps.map(e => `
        <tr id="row-${e.id}">
            <td>${escHtml(e.nombre)}</td>
            <td>
                <span class="badge-${e.activa == 1 ? 'activa' : 'inactiva'}">
                    ${e.activa == 1 ? 'Activa' : 'Inactiva'}
                </span>
            </td>
            <td class="d-flex gap-1">
                <button class="btn btn-outline-secondary btn-sm" title="Editar" onclick="abrirModal(${e.id},'${escHtml(e.nombre).replace(/'/g,"\\'")}')">
                    <i class="fas fa-pen"></i>
                </button>
                <button class="btn btn-outline-${e.activa == 1 ? 'warning' : 'success'} btn-sm" title="${e.activa == 1 ? 'Desactivar' : 'Activar'}" onclick="toggleEps(${e.id})">
                    <i class="fas fa-${e.activa == 1 ? 'ban' : 'check'}"></i>
                </button>
                <button class="btn btn-outline-danger btn-sm" title="Eliminar" onclick="eliminarEps(${e.id},'${escHtml(e.nombre).replace(/'/g,"\\'")}')">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function abrirModal(id = 0, nombre = '') {
    document.getElementById('eps-id').value    = id;
    document.getElementById('eps-nombre').value = nombre;
    document.getElementById('eps-error').classList.add('d-none');
    document.getElementById('modal-eps-titulo').textContent = id ? 'Editar EPS' : 'Nueva EPS';
    _modal = _modal || new bootstrap.Modal(document.getElementById('modal-eps'));
    _modal.show();
    setTimeout(() => document.getElementById('eps-nombre').focus(), 300);
}

async function guardarEps() {
    const nombre = document.getElementById('eps-nombre').value.trim();
    const id     = parseInt(document.getElementById('eps-id').value) || 0;
    const errEl  = document.getElementById('eps-error');
    errEl.classList.add('d-none');
    if (!nombre) { errEl.textContent = 'El nombre es requerido.'; errEl.classList.remove('d-none'); return; }

    const r = await fetch(API_EPS, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'save', id, nombre }),
    });
    const j = await r.json();
    if (!j.ok) { errEl.textContent = j.error || 'Error'; errEl.classList.remove('d-none'); return; }
    _modal.hide();
    cargarEps();
}

async function toggleEps(id) {
    await fetch(API_EPS, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'toggle', id }),
    });
    cargarEps();
}

async function eliminarEps(id, nombre) {
    if (!confirm(`¿Eliminar "${nombre}"?`)) return;
    const r = await fetch(API_EPS, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'delete', id }),
    });
    const j = await r.json();
    if (!j.ok) { alert(j.error); return; }
    cargarEps();
}

function escHtml(str) {
    const d = document.createElement('div');
    d.appendChild(document.createTextNode(String(str)));
    return d.innerHTML;
}

document.getElementById('eps-nombre').addEventListener('keydown', e => {
    if (e.key === 'Enter') guardarEps();
});

cargarEps();
</script>
</body>
</html>
