<?php /** ASISMA CRM - Verticales CRUD (catalogo 100% del CRM) */ ?>
<?php
$puedeEditarCatalogo = SessionHelper::isAdmin();
?>

<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">Verticales de Negocio</h1>
        <p class="text-slate-400 text-sm mt-1">Estructura base de las lineas comerciales del sistema.</p>
    </div>
    <?php if ($puedeEditarCatalogo): ?>
    <button onclick="openModal()" class="inline-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-colors shadow-lg">
        <i data-lucide="plus" class="w-4 h-4"></i> Nueva Vertical
    </button>
    <?php endif; ?>
</div>

<div class="mb-4 flex justify-end">
    <a href="?inactivos=<?php echo $mostrarInactivos ? '0' : '1'; ?>" class="inline-flex items-center gap-1.5 text-xs font-semibold text-slate-400 hover:text-slate-200 transition-colors">
        <i data-lucide="<?php echo $mostrarInactivos ? 'eye-off' : 'eye'; ?>" class="w-3.5 h-3.5"></i>
        <?php echo $mostrarInactivos ? 'Ocultar inactivos (mostrar solo activos)' : 'Mostrar tambien los inactivos'; ?>
    </a>
</div>

<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">ID</th>
                    <th class="px-6 py-4 font-semibold">Nombre</th>
                    <th class="px-6 py-4 font-semibold">Descripcion</th>
                    <th class="px-6 py-4 font-semibold text-center">Estado</th>
                    <?php if ($puedeEditarCatalogo): ?>
                    <th class="px-6 py-4 font-semibold text-right">Acciones</th>
                    <?php endif; ?>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800 text-slate-300">
                <?php if (empty($verticales)): ?>
                <tr><td colspan="5" class="px-6 py-10 text-center text-slate-500">No hay verticales registradas.</td></tr>
                <?php else: ?>
                <?php foreach ($verticales as $v): ?>
                <tr class="hover:bg-slate-800/30 transition-colors">
                    <td class="px-6 py-4 font-mono text-slate-500 text-xs">#<?php echo $v['id']; ?></td>
                    <td class="px-6 py-4 font-bold text-slate-100"><?php echo htmlspecialchars($v['nombre']); ?></td>
                    <td class="px-6 py-4 text-slate-400 text-xs"><?php echo htmlspecialchars(isset($v['descripcion']) ? $v['descripcion'] : '-'); ?></td>
                    <td class="px-6 py-4 text-center">
                        <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold <?php echo $v['activa'] ? 'bg-green-500/10 text-green-400 border border-green-500/20' : 'bg-red-500/10 text-red-400 border border-red-500/20'; ?>">
                            <?php echo $v['activa'] ? 'Activa' : 'Inactiva'; ?>
                        </span>
                    </td>
                    <?php if ($puedeEditarCatalogo): ?>
                    <td class="px-6 py-4 text-right space-x-2">
                        <button onclick='openModal(<?php echo json_encode($v); ?>)' class="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-lg text-xs font-semibold transition-colors border border-slate-700">Editar</button>
                        <button onclick="toggleEstado(<?php echo $v['id']; ?>, <?php echo $v['activa'] ? 0 : 1; ?>)"
                                class="px-3 py-1.5 <?php echo $v['activa'] ? 'bg-red-950/30 hover:bg-red-950/50 text-red-400 border border-red-900/30' : 'bg-green-950/30 hover:bg-green-950/50 text-green-400 border border-green-900/30'; ?> rounded-lg text-xs font-semibold transition-colors">
                            <?php echo $v['activa'] ? 'Desactivar' : 'Activar'; ?>
                        </button>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal -->
<div id="modalOverlay" class="fixed inset-0 z-50 flex items-center justify-center hidden bg-slate-950/70 backdrop-blur-sm px-4">
    <div class="bg-slate-900 border border-slate-800 rounded-2xl w-full max-w-md p-6 shadow-2xl">
        <h3 id="modalTitle" class="text-lg font-bold text-white mb-5">Nueva Vertical</h3>
        <form id="modalForm" class="space-y-4">
            <input type="hidden" id="fId" name="id" value="">
            <div>
                <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1.5">Nombre *</label>
                <input type="text" id="fNombre" name="nombre" required
                       class="block w-full px-3 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1.5">Descripcion</label>
                <textarea id="fDescripcion" name="descripcion" rows="2"
                          class="block w-full px-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
            </div>
            <div class="flex justify-end gap-4 pt-4 border-t border-slate-800">
                <button type="button" onclick="closeModal()" class="px-4 py-2 bg-slate-950 border border-red-500/40 hover:border-red-500/70 hover:bg-red-500/10 text-red-400 text-xs font-semibold rounded-lg transition-colors">Cancelar</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold rounded-lg transition-colors">Guardar</button>
            </div>
        </form>
    </div>
</div>

<script>
var APP_URL = '<?php echo APP_URL; ?>';

function openModal(data) {
    if (data) {
        document.getElementById('modalTitle').textContent = 'Editar Vertical';
        document.getElementById('fId').value = data.id;
        document.getElementById('fNombre').value = data.nombre;
        document.getElementById('fDescripcion').value = data.descripcion || '';
    } else {
        document.getElementById('modalTitle').textContent = 'Nueva Vertical';
        document.getElementById('modalForm').reset();
        document.getElementById('fId').value = '';
    }
    document.getElementById('modalOverlay').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('modalOverlay').classList.add('hidden');
}

document.getElementById('modalForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var id  = document.getElementById('fId').value;
    var url = id ? APP_URL + '/verticales/editar' : APP_URL + '/verticales/crear';
    var fd  = new FormData(this);
    $.ajax({
        url: url, type: 'POST', data: $(this).serialize(), dataType: 'json',
        success: function(r) {
            if (r.success) {
                Swal.fire({ icon: 'success', title: 'Listo', text: r.message, background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#3b82f6', timer: 1400, showConfirmButton: false })
                    .then(function() { location.reload(); });
            } else {
                Swal.fire({ icon: 'error', title: 'Error', text: r.message, background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#ef4444' });
            }
        }
    });
});

function toggleEstado(id, nuevoEstado) {
    var msg = nuevoEstado === 0 ? 'desactivar esta vertical' : 'activar esta vertical';
    Swal.fire({
        title: 'Confirmar', text: '¿Deseas ' + msg + '?', icon: 'question',
        showCancelButton: true, confirmButtonText: 'Si, continuar', cancelButtonText: 'Cancelar',
        background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#3b82f6'
    }).then(function(result) {
        if (result.isConfirmed) {
            $.post(APP_URL + '/verticales/toggle', { id: id }, function(r) {
                if (r.success) { location.reload(); }
                else { Swal.fire({ icon: 'error', title: 'Error', text: r.message, background: '#1e293b', color: '#f8fafc' }); }
            }, 'json');
        }
    });
}
</script>
