<?php
/**
 * ASISMA CRM - Listado de Empresas
 */
?>
<!-- Header -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
    <div>
        <h1 class="text-3xl font-extrabold text-white tracking-tight">Directorio de Empresas</h1>
        <p class="text-slate-400 text-sm mt-1">Empresas clientes que han solicitado información o cotizado productos.</p>
    </div>
    <button id="btnNuevaEmpresa"
            class="flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-500 text-white text-sm font-semibold rounded-xl transition-all shadow-md shadow-blue-600/10">
        <i data-lucide="plus" class="w-4 h-4"></i>
        <span>Nueva Empresa</span>
    </button>
</div>

<!-- Table Card -->
<div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden shadow-xl">
    <div class="overflow-x-auto">
        <table class="w-full text-left text-sm border-collapse">
            <thead>
                <tr class="bg-slate-950 border-b border-slate-800 text-slate-400 uppercase text-xs tracking-wider">
                    <th class="px-6 py-4 font-semibold">Razón Social / RUT</th>
                    <th class="px-6 py-4 font-semibold">Giro / Actividad</th>
                    <th class="px-6 py-4 font-semibold">Ubicación</th>
                    <th class="px-6 py-4 font-semibold">Contacto</th>
                    <th class="px-6 py-4 font-semibold text-right">Acciones</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-850 text-slate-300">
                <?php if (empty($empresas)): ?>
                    <tr>
                        <td colspan="5" class="px-6 py-12 text-center text-slate-500">No hay empresas registradas aún.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($empresas as $e): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors <?php echo !$e['activa'] ? 'opacity-50' : ''; ?>">
                            <td class="px-6 py-4">
                                <div class="font-bold text-slate-100"><?php echo htmlspecialchars($e['razon_social']); ?></div>
                                <?php if (!empty($e['rut'])): ?>
                                <div class="text-xs text-slate-500 mt-0.5 font-mono"><?php echo htmlspecialchars($e['rut']); ?></div>
                                <?php endif; ?>
                                <?php if (!$e['activa']): ?>
                                <span class="text-[10px] text-red-400 bg-red-500/10 px-1.5 py-0.5 rounded">Inactiva</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 text-xs text-slate-300">
                                <?php echo htmlspecialchars($e['giro'] ? $e['giro'] : 'No registrado'); ?>
                            </td>
                            <td class="px-6 py-4 text-xs text-slate-400">
                                <div><?php echo htmlspecialchars($e['direccion'] ? $e['direccion'] : 'Sin dirección'); ?></div>
                                <?php if (!empty($e['region_nombre'])): ?>
                                <div class="text-[10px] text-slate-500 mt-0.5"><?php echo htmlspecialchars($e['region_nombre']); ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 text-xs font-mono">
                                <div><?php echo htmlspecialchars($e['telefono'] ? $e['telefono'] : 'N/A'); ?></div>
                                <div class="text-slate-500 mt-0.5"><?php echo htmlspecialchars($e['email'] ? $e['email'] : 'N/A'); ?></div>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <div class="flex items-center justify-end gap-2">
                                    <button class="btn-editar p-1.5 text-slate-400 hover:text-blue-400 transition-colors"
                                            data-id="<?php echo $e['id']; ?>" title="Editar">
                                        <i data-lucide="pencil" class="w-4 h-4"></i>
                                    </button>
                                    <button class="btn-toggle p-1.5 transition-colors <?php echo $e['activa'] ? 'text-slate-400 hover:text-amber-400' : 'text-slate-600 hover:text-emerald-400'; ?>"
                                            data-id="<?php echo $e['id']; ?>" data-activa="<?php echo $e['activa']; ?>"
                                            title="<?php echo $e['activa'] ? 'Desactivar' : 'Activar'; ?>">
                                        <i data-lucide="<?php echo $e['activa'] ? 'eye-off' : 'eye'; ?>" class="w-4 h-4"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Crear/Editar Empresa -->
<div id="modalEmpresa" class="hidden fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
    <div class="bg-slate-900 border border-slate-800 rounded-2xl p-8 w-full max-w-xl shadow-2xl">
        <div class="flex items-center justify-between mb-6">
            <h2 id="modalTitle" class="text-xl font-bold text-white">Nueva Empresa</h2>
            <button id="btnCerrarModal" class="p-2 text-slate-400 hover:text-white transition-colors">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        <form id="formEmpresa" class="space-y-4">
            <input type="hidden" id="empresaId" name="id" value="">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="md:col-span-2">
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1">Razón Social *</label>
                    <input type="text" name="razon_social" id="razon_social" required
                           class="block w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="Nombre de la empresa">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1">RUT</label>
                    <input type="text" name="rut" id="empresaRut"
                           class="block w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="12345678-9">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1">Región</label>
                    <select name="region_id" id="empresaRegion"
                            class="block w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">-- Seleccionar --</option>
                        <?php foreach ($regiones as $r): ?>
                        <option value="<?php echo $r['id']; ?>"><?php echo htmlspecialchars($r['nombre']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="md:col-span-2">
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1">Giro / Actividad</label>
                    <input type="text" name="giro" id="empresaGiro"
                           class="block w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="Comercio al por menor...">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1">Teléfono</label>
                    <input type="text" name="telefono" id="empresaTelefono"
                           class="block w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="+56212345678">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1">Email</label>
                    <input type="email" name="email" id="empresaEmail"
                           class="block w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="contacto@empresa.cl">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1">Dirección</label>
                    <input type="text" name="direccion" id="empresaDireccion"
                           class="block w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="Av. Ejemplo 123, Santiago">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1">Sitio Web</label>
                    <input type="text" name="web" id="empresaWeb"
                           class="block w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="www.empresa.cl">
                </div>
            </div>
            <div class="flex justify-end gap-4 pt-4 border-t border-slate-800">
                <button type="button" id="btnCancelar"
                        class="px-4 py-2 bg-slate-950 hover:bg-red-500/10 border border-red-500/40 hover:border-red-500/70 text-red-400 text-sm font-medium rounded-xl transition-colors">
                    Cancelar
                </button>
                <button type="submit" id="btnSubmitEmpresa"
                        class="px-5 py-2 bg-blue-600 hover:bg-blue-500 text-white text-sm font-semibold rounded-xl transition-colors">
                    Guardar
                </button>
            </div>
        </form>
    </div>
</div>

<script>
$(document).ready(function() {

    function abrirModal(titulo, datos) {
        $('#modalTitle').text(titulo);
        $('#empresaId').val(datos.id || '');
        $('input[name="razon_social"]').val(datos.razon_social || '');
        $('#empresaRut').val(datos.rut || '');
        $('#empresaGiro').val(datos.giro || '');
        $('#empresaRegion').val(datos.region_id || '');
        $('#empresaTelefono').val(datos.telefono || '');
        $('#empresaEmail').val(datos.email || '');
        $('#empresaDireccion').val(datos.direccion || '');
        $('#empresaWeb').val(datos.sitio_web || datos.web || '');
        $('#modalEmpresa').removeClass('hidden');
    }

    function cerrarModal() { $('#modalEmpresa').addClass('hidden'); }

    $('#btnNuevaEmpresa').on('click', function() { abrirModal('Nueva Empresa', {}); });
    $('#btnCerrarModal, #btnCancelar').on('click', cerrarModal);

    $(document).on('click', '.btn-editar', function() {
        const id = $(this).data('id');
        $.get('<?php echo APP_URL; ?>/empresas/data', { id: id }, function(r) {
            if (r.success) abrirModal('Editar Empresa', r.data);
            else Swal.fire({ icon: 'error', title: 'Error', text: r.message, background: '#1e293b', color: '#f8fafc' });
        }, 'json');
    });

    $('#formEmpresa').on('submit', function(e) {
        e.preventDefault();
        const id = $('#empresaId').val();
        const url = id ? '<?php echo APP_URL; ?>/empresas/editar' : '<?php echo APP_URL; ?>/empresas/crear';
        $.post(url, $(this).serialize(), function(r) {
            if (r.success) {
                Swal.fire({ toast: true, position: 'top-end', icon: 'success', title: r.message, background: '#1e293b', color: '#f8fafc', showConfirmButton: false, timer: 1800 });
                setTimeout(function() { location.reload(); }, 1000);
                cerrarModal();
            } else {
                Swal.fire({ icon: 'error', title: 'Error', text: r.message, background: '#1e293b', color: '#f8fafc' });
            }
        }, 'json');
    });

    $(document).on('click', '.btn-toggle', function() {
        const id = $(this).data('id');
        const activa = $(this).data('activa');
        const accion = activa == 1 ? 'desactivar' : 'activar';
        Swal.fire({
            title: '¿' + accion.charAt(0).toUpperCase() + accion.slice(1) + ' empresa?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, ' + accion,
            cancelButtonText: 'Cancelar',
            background: '#1e293b',
            color: '#f8fafc',
            confirmButtonColor: '#3b82f6'
        }).then(function(r) {
            if (r.isConfirmed) {
                $.post('<?php echo APP_URL; ?>/empresas/toggle', { id: id }, function(res) {
                    if (res.success) { location.reload(); }
                    else Swal.fire({ icon: 'error', title: 'Error', text: res.message, background: '#1e293b', color: '#f8fafc' });
                }, 'json');
            }
        });
    });
});
</script>
