<!DOCTYPE html>
<html lang="es" class="{{ 'dark' if tema == 1 else '' }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>UTRAU - Empresas y Organismos</title>

    <!-- Favicon y App Icons -->
    <link rel="apple-touch-icon" sizes="180x180" href="{{ url_for('static', filename='apple-touch-icon.png') }}">
    <link rel="icon" type="image/png" sizes="32x32" href="{{ url_for('static', filename='favicon-32x32.png') }}">
    <link rel="icon" type="image/png" sizes="16x16" href="{{ url_for('static', filename='favicon-16x16.png') }}">
    <link rel="manifest" href="{{ url_for('static', filename='site.webmanifest') }}">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">

    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script>
        tailwind.config = { darkMode: 'class', theme: { extend: {} } }
    </script>
</head>
<body class="bg-slate-100 dark:bg-slate-950 text-slate-900 dark:text-slate-100 transition-colors duration-300 min-h-screen">

    <nav class="bg-slate-900 border-b border-slate-800 p-4 flex justify-between items-center shadow-md text-white sticky top-0 z-40">
        <div class="flex items-center space-x-3">
            <span class="font-black text-sky-500">UTRAU <span class="text-slate-400 font-bold hidden sm:inline">| ENTIDADES INSTITUCIONALES</span></span>
        </div>
        <a href="{{ url_for('config.panel') }}" class="text-xs font-bold uppercase text-slate-400 hover:text-white transition"><i class="fa-solid fa-arrow-left mr-2"></i>Volver</a>
    </nav>

    <div class="max-w-7xl mx-auto px-6 mt-4">
        {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
        {% for category, message in messages %}
        {% if category == 'success' %}
        <div class="bg-emerald-100 dark:bg-emerald-900/30 border border-emerald-500 text-emerald-700 dark:text-emerald-400 px-4 py-3 rounded-xl flex items-center mb-4 shadow-sm">
            <i class="fa-solid fa-circle-check mr-3 text-lg"></i><span class="text-sm font-bold">{{ message }}</span>
        </div>
        {% elif category == 'error' %}
        <div class="bg-red-100 dark:bg-red-900/30 border border-red-500 text-red-700 dark:text-red-400 px-4 py-3 rounded-xl flex items-center mb-4 shadow-sm">
            <i class="fa-solid fa-triangle-exclamation mr-3 text-lg"></i><span class="text-sm font-bold">{{ message }}</span>
        </div>
        {% endif %}
        {% endfor %}
        {% endif %}
        {% endwith %}
    </div>

    <main class="p-6 max-w-7xl mx-auto grid grid-cols-1 xl:grid-cols-5 gap-6 items-start">
        
        <!-- COLUMNA IZQ: LISTADO -->
        <div id="seccion_lista" class="xl:col-span-2 bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm overflow-hidden h-[50vh] xl:h-[85vh] flex flex-col scroll-mt-20">
            <div class="p-6 border-b border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/50">
                <div class="flex justify-between items-start">
                    <div class="w-full">
                        <h2 class="text-xl font-black uppercase tracking-tight">Directorio</h2>
                        <input type="text" id="buscador" onkeyup="filtrarEmpresas()" placeholder="🔍 Buscar empresa o entidad..." class="w-full mt-3 px-3 py-2 rounded-lg bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-700 text-slate-800 dark:text-white text-xs font-bold outline-none focus:border-sky-500">
                        <p class="text-[10px] text-slate-500 font-bold mt-2">Empresas, MTSS, Sindicatos.</p>
                    </div>
                    <button onclick="limpiarFormulario()" class="ml-4 px-3 py-2 bg-sky-600 hover:bg-sky-700 text-white text-[10px] font-black uppercase tracking-wider rounded-lg transition shadow-md whitespace-nowrap">+ Nuevo</button>
                </div>
            </div>

            <div class="overflow-y-auto flex-1 p-2">
                {% for emp in lista_empresas %}
                <div class="empresa-card border border-slate-200 dark:border-slate-800 rounded-xl mb-3 p-4 hover:border-sky-500 transition group relative">
                    <div class="flex justify-between items-start mb-1">
                        <h4 class="font-black text-slate-800 dark:text-slate-100">{{ emp.nombre_fantasia }}</h4>
                        <span class="text-[9px] font-black uppercase tracking-widest px-2 py-0.5 rounded bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-400">{{ emp.tipo }}</span>
                    </div>
                    <p class="text-[10px] font-bold text-slate-500 uppercase tracking-widest">{{ emp.nombre_fiscal }} | RUT: {{ emp.rut or 'N/D' }}</p>
                    <p class="text-xs text-slate-600 dark:text-slate-400 mt-2"><i class="fa-solid fa-location-dot mr-1 text-slate-400"></i> {{ emp.localidad or 'S/D' }}, {{ emp.departamento or 'S/D' }}</p>

                    <!-- Contactos Vinculados -->
                    <div class="mt-3 pt-3 border-t border-slate-100 dark:border-slate-800">
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-[10px] font-black uppercase tracking-widest text-slate-400">Contactos</span>
                            <button onclick="abrirModalContacto('{{ emp.id_empresa }}', '{{ emp.nombre_fantasia }}')" class="text-[9px] font-black uppercase bg-emerald-100 hover:bg-emerald-200 text-emerald-700 px-2 py-1 rounded transition">+ Contacto</button>
                        </div>
                        {% for c in emp.contactos %}
                        <div class="bg-slate-50 dark:bg-slate-800/50 p-2 rounded mb-1 border border-slate-100 dark:border-slate-800">
                            <p class="text-xs font-bold text-slate-800 dark:text-slate-200"><i class="fa-solid fa-user-tie text-[10px] mr-1 text-slate-400"></i> {{ c.nombre }} <span class="font-normal text-slate-500">({{ c.cargo or 'Sin Cargo' }})</span></p>
                            <p class="text-[10px] font-medium text-slate-500 ml-4"><i class="fa-solid fa-phone mr-1"></i> {{ c.celular_whatsapp or '-' }} | <i class="fa-solid fa-envelope mr-1"></i> {{ c.email or '-' }}</p>
                        </div>
                        {% else %}
                        <p class="text-[10px] font-bold text-slate-400 italic">No hay contactos registrados.</p>
                        {% endfor %}
                    </div>

                    <!-- Botón de Edición -->
                    <button onclick="editarEmpresa('{{ emp.id_empresa }}', '{{ emp.nombre_fantasia }}', '{{ emp.nombre_fiscal }}', '{{ emp.rut or '' }}', '{{ emp.direccion or '' }}', '{{ emp.localidad or '' }}', '{{ emp.departamento or '' }}', '{{ emp.mail_oficial or '' }}', '{{ emp.cant_trabajadores }}', '{{ emp.tipo }}', '{{ emp.estado }}')" class="absolute top-4 right-4 opacity-0 group-hover:opacity-100 p-2 bg-sky-100 hover:bg-sky-500 hover:text-white text-sky-700 rounded-lg transition" title="Editar Expediente">
                        <i class="fa-solid fa-pen"></i>
                    </button>
                </div>
                {% endfor %}
            </div>
        </div>

        <!-- COLUMNA DER: FORMULARIO ABML -->
        <div id="seccion_formulario" class="xl:col-span-3 bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm h-fit mb-10 scroll-mt-20">
            <div class="p-6 border-b border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/50 flex justify-between items-center">
                <h2 class="text-lg font-black uppercase tracking-tight" id="titulo_formulario">Nueva Entidad</h2>
            </div>
            
            <div class="p-6">
                <form action="{{ url_for('config.guardar_empresa_crm') }}" method="POST" class="space-y-6">
                    <input type="hidden" name="id_empresa" id="form_id_empresa" value="">
                    
                    <div>
                        <h3 class="text-xs font-black uppercase text-slate-400 border-b border-slate-200 dark:border-slate-800 pb-2 mb-4"><i class="fa-solid fa-building mr-2"></i>Identidad Institucional</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Nombre Fantasía*</label>
                                <input type="text" name="nombre_fantasia" id="form_nombre_fantasia" required class="w-full px-4 py-2 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-transparent focus:border-sky-500 outline-none font-bold text-sm">
                            </div>
                            <div>
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Razón Social (Fiscal)*</label>
                                <input type="text" name="nombre_fiscal" id="form_nombre_fiscal" required class="w-full px-4 py-2 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-transparent focus:border-sky-500 outline-none font-bold text-sm">
                            </div>
                            <div>
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">RUT</label>
                                <input type="text" name="rut" id="form_rut" class="w-full px-4 py-2 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-transparent focus:border-sky-500 outline-none font-bold text-sm">
                            </div>
                            <div>
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Tipo de Entidad*</label>
                                <select name="tipo" id="form_tipo" class="w-full px-4 py-2.5 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-transparent focus:border-sky-500 outline-none font-bold text-sm">
                                    <option value="Empresa" class="text-black">Empresa Privada</option>
                                    <option value="MTSS/IGTSS" class="text-black">MTSS / IGTSS</option>
                                    <option value="Sindicato" class="text-black">Sindicato / PIT-CNT</option>
                                    <option value="Judicial" class="text-black">Juzgado / Sede Judicial</option>
                                    <option value="Otro" class="text-black">Otro Organismo</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div>
                        <h3 class="text-xs font-black uppercase text-slate-400 border-b border-slate-200 dark:border-slate-800 pb-2 mb-4"><i class="fa-solid fa-map-location-dot mr-2"></i>Ubicación y Operativa</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div class="md:col-span-3">
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Dirección Física</label>
                                <input type="text" name="direccion" id="form_direccion" class="w-full px-4 py-2 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-transparent focus:border-sky-500 outline-none font-bold text-sm">
                            </div>
                            <div>
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Localidad</label>
                                <input type="text" name="localidad" id="form_localidad" class="w-full px-4 py-2 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-transparent focus:border-sky-500 outline-none font-bold text-sm">
                            </div>
                            <div>
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Departamento</label>
                                <input type="text" name="departamento" id="form_departamento" class="w-full px-4 py-2 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-transparent focus:border-sky-500 outline-none font-bold text-sm">
                            </div>
                            <div>
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Email Institucional</label>
                                <input type="email" name="mail_oficial" id="form_mail_oficial" class="w-full px-4 py-2 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-transparent focus:border-sky-500 outline-none font-bold text-sm">
                            </div>
                        </div>
                    </div>

                    <div class="pt-4 border-t border-slate-100 dark:border-slate-800 flex justify-between items-center space-x-4">
                        <div class="flex-1 grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Trabajadores (Fuerza)</label>
                                <input type="number" name="cant_trabajadores" id="form_cant_trabajadores" value="0" class="w-full px-4 py-3 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-transparent focus:border-sky-500 outline-none font-black text-sm">
                                <p class="text-[9px] font-bold text-slate-400 mt-1">Dejar 0 para MTSS/Juzgados.</p>
                            </div>
                            <div>
                                <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Estado Registral</label>
                                <select name="estado" id="form_estado" class="w-full px-4 py-3 rounded-xl border-2 border-slate-200 dark:border-slate-800 bg-slate-100 dark:bg-slate-900 focus:border-sky-500 font-black text-sm">
                                    <option value="Activa" class="text-black">Activa (Operativa)</option>
                                    <option value="En Conflicto" class="text-amber-600 font-bold">En Conflicto</option>
                                    <option value="Archivada" class="text-slate-400">Archivada (Cerrada)</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="w-full bg-sky-600 hover:bg-sky-700 text-white font-black py-4 rounded-xl transition-all uppercase tracking-wider text-sm shadow-md mt-4">
                        <i class="fa-solid fa-save mr-2"></i>Guardar Expediente
                    </button>
                </form>
            </div>
        </div>
    </main>

    <!-- MODAL: AGREGAR CONTACTO -->
    <div id="modalContacto" class="fixed inset-0 bg-slate-900/60 z-50 hidden flex items-center justify-center backdrop-blur-sm p-4">
        <div class="bg-white dark:bg-slate-900 p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-slate-200 dark:border-slate-800">
            <div class="flex justify-between items-center mb-4 border-b border-slate-100 dark:border-slate-800 pb-2">
                <h3 class="text-lg font-black uppercase tracking-tight text-emerald-600"><i class="fa-solid fa-address-book mr-2"></i>Nuevo Contacto</h3>
                <button type="button" onclick="cerrarModalContacto()" class="text-slate-400 hover:text-red-500"><i class="fa-solid fa-xmark text-xl"></i></button>
            </div>
            
            <p class="text-xs font-bold text-slate-500 mb-4 uppercase tracking-widest">Para: <span id="lbl_empresa_contacto" class="text-slate-800 dark:text-slate-200 font-black"></span></p>

            <form action="{{ url_for('config.guardar_contacto') }}" method="POST" class="space-y-4">
                <input type="hidden" name="id_empresa_contacto" id="form_id_empresa_contacto">
                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Nombre Completo*</label>
                    <input type="text" name="nombre_contacto" required class="w-full px-4 py-2 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-emerald-500 font-bold text-sm">
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Cargo / Puesto (Ej: Jefa RRHH)</label>
                    <input type="text" name="cargo_contacto" class="w-full px-4 py-2 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-emerald-500 font-bold text-sm">
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Celular / Teléfono Directo</label>
                    <input type="text" name="celular_contacto" class="w-full px-4 py-2 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-emerald-500 font-bold text-sm">
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Email</label>
                    <input type="email" name="email_contacto" class="w-full px-4 py-2 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-emerald-500 font-bold text-sm">
                </div>
                <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-black py-3 rounded-xl mt-4 transition uppercase tracking-wider text-sm">Guardar Contacto</button>
            </form>
        </div>
    </div>

    <script>
        function editarEmpresa(id, fantasia, fiscal, rut, dir, loc, dep, mail, cant, tipo, estado) {
            document.getElementById('titulo_formulario').innerText = "Editando: " + fantasia;
            document.getElementById('form_id_empresa').value = id;
            document.getElementById('form_nombre_fantasia').value = fantasia;
            document.getElementById('form_nombre_fiscal').value = fiscal;
            document.getElementById('form_rut').value = rut;
            document.getElementById('form_direccion').value = dir;
            document.getElementById('form_localidad').value = loc;
            document.getElementById('form_departamento').value = dep;
            document.getElementById('form_mail_oficial').value = mail;
            document.getElementById('form_cant_trabajadores').value = cant;
            document.getElementById('form_tipo').value = tipo;
            document.getElementById('form_estado').value = estado;
            document.getElementById('seccion_formulario').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function limpiarFormulario() {
            document.getElementById('titulo_formulario').innerText = "Nueva Entidad";
            document.getElementById('form_id_empresa').value = "";
            document.getElementById('form_nombre_fantasia').value = "";
            document.getElementById('form_nombre_fiscal').value = "";
            document.getElementById('form_rut').value = "";
            document.getElementById('form_direccion').value = "";
            document.getElementById('form_localidad').value = "";
            document.getElementById('form_departamento').value = "";
            document.getElementById('form_mail_oficial').value = "";
            document.getElementById('form_cant_trabajadores').value = "0";
            document.getElementById('form_tipo').value = "Empresa";
            document.getElementById('form_estado').value = "Activa";
            document.getElementById('seccion_formulario').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function abrirModalContacto(id_empresa, nombre_fantasia) {
            document.getElementById('form_id_empresa_contacto').value = id_empresa;
            document.getElementById('lbl_empresa_contacto').innerText = nombre_fantasia;
            document.getElementById('modalContacto').classList.remove('hidden');
            document.getElementById('modalContacto').classList.add('flex');
        }

        function cerrarModalContacto() {
            document.getElementById('modalContacto').classList.add('hidden');
            document.getElementById('modalContacto').classList.remove('flex');
        }

        // BUSCADOR EN TIEMPO REAL
        function filtrarEmpresas() {
            let input = document.getElementById('buscador').value.toUpperCase();
            let cards = document.getElementsByClassName('empresa-card');
            
            for (let i = 0; i < cards.length; i++) {
                let titulo = cards[i].querySelector('h4').innerText.toUpperCase();
                if (titulo.indexOf(input) > -1) {
                    cards[i].style.display = "";
                } else {
                    cards[i].style.display = "none";
                }
            }
        }
    </script>
</body>
</html>