<?php
/**
 * ASISMA CRM - Cola de Asignación de Leads por Franquiciado
 */
?>
<div class="mb-8">
    <a href="<?php echo APP_URL; ?>/franquiciados" class="inline-flex items-center gap-1.5 text-xs text-slate-500 hover:text-slate-300 font-semibold mb-3">
        <i data-lucide="arrow-left" class="w-3.5 h-3.5"></i>
        <span>Volver a Franquiciados</span>
    </a>
    <h1 class="text-3xl font-extrabold text-white tracking-tight">Cola de Asignación</h1>
    <p class="text-slate-400 text-sm mt-1">Configure qué vendedores reciben leads y en qué orden (rotación circular).</p>
</div>

<!-- Selector de franquiciado -->
<div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 mb-8 shadow-xl">
    <form method="GET" action="<?php echo APP_URL; ?>/franquiciados/cola" class="flex items-end gap-4">
        <div class="flex-1 max-w-sm">
            <label class="block text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Seleccionar Franquiciado</label>
            <select name="franquiciado_id" onchange="this.form.submit()"
                    class="block w-full px-3 py-2.5 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 ($franquiciados as $f): ?>
                    <option value="<?php echo $f['id']; ?>" <?php echo $franquiciadoId == $f['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($f['nombre_fantasia']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
    </form>
</div>

<?php if ($franquiciadoId > 0): ?>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">

    <!-- Cola actual -->
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 shadow-xl">
        <h3 class="text-sm font-bold text-white uppercase tracking-wider border-b border-slate-800 pb-2 mb-6 flex items-center gap-2">
            <i data-lucide="list-ordered" class="w-4 h-4 text-blue-500"></i>
            Cola Actual
            <span class="ml-auto text-xs text-slate-500 normal-case font-normal">Arrastra para reordenar</span>
        </h3>

        <?php if (empty($colaActual)): ?>
        <div class="text-center py-8 text-slate-500">
            <i data-lucide="inbox" class="w-8 h-8 mx-auto mb-2 text-slate-600"></i>
            <p class="text-sm">No hay vendedores en la cola.</p>
        </div>
        <?php else: ?>
        <ul id="sortableList" class="space-y-2">
            <?php foreach ($colaActual as $item): ?>
            <li class="flex items-center gap-3 px-4 py-3 bg-slate-950 border border-slate-800 rounded-xl cursor-grab group" data-uid="<?php echo $item['usuario_id']; ?>">
                <i data-lucide="grip-vertical" class="w-4 h-4 text-slate-600 group-hover:text-slate-400 shrink-0"></i>
                <div class="flex-1 min-w-0">
                    <div class="font-semibold text-slate-200 text-sm"><?php echo htmlspecialchars($item['usuario_nombre']); ?></div>
                    <div class="text-xs text-slate-500"><?php echo htmlspecialchars($item['usuario_email']); ?></div>
                </div>
                <span class="text-[10px] font-bold text-slate-600 bg-slate-800 px-2 py-1 rounded-md">#<?php echo $item['orden']; ?></span>
                <button class="btn-quitar text-slate-500 hover:text-red-400 transition-colors" data-uid="<?php echo $item['usuario_id']; ?>" title="Quitar de la cola">
                    <i data-lucide="x" class="w-4 h-4"></i>
                </button>
            </li>
            <?php endforeach; ?>
        </ul>
        <button id="btnGuardarOrden" class="mt-4 w-full py-2 bg-blue-600 hover:bg-blue-500 text-white text-sm font-semibold rounded-xl transition-colors">
            Guardar Orden
        </button>
        <?php endif; ?>
    </div>

    <!-- Vendedores disponibles -->
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 shadow-xl">
        <h3 class="text-sm font-bold text-white uppercase tracking-wider border-b border-slate-800 pb-2 mb-6 flex items-center gap-2">
            <i data-lucide="users" class="w-4 h-4 text-emerald-500"></i>
            Vendedores del Franquiciado
        </h3>

        <?php if (empty($usuariosDisponibles)): ?>
        <div class="text-center py-8 text-slate-500">
            <i data-lucide="user-x" class="w-8 h-8 mx-auto mb-2 text-slate-600"></i>
            <p class="text-sm">No hay vendedores activos en este franquiciado.</p>
        </div>
        <?php else: ?>
        <ul class="space-y-2">
            <?php
            $idsEnCola = array_column($colaActual, 'usuario_id');
            foreach ($usuariosDisponibles as $usr):
                $yaEnCola = in_array($usr['id'], $idsEnCola);
            ?>
            <li class="flex items-center gap-3 px-4 py-3 bg-slate-950 border border-slate-800 rounded-xl">
                <div class="w-8 h-8 rounded-full bg-slate-800 flex items-center justify-center text-slate-300 font-bold text-xs shrink-0">
                    <?php echo strtoupper(substr($usr['nombre'], 0, 1)); ?>
                </div>
                <div class="flex-1 min-w-0">
                    <div class="font-semibold text-slate-200 text-sm"><?php echo htmlspecialchars($usr['nombre']); ?></div>
                    <div class="text-xs text-slate-500"><?php echo htmlspecialchars($usr['email']); ?></div>
                </div>
                <?php if ($yaEnCola): ?>
                <span class="text-xs text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-full border border-emerald-500/20">En cola</span>
                <?php else: ?>
                <button class="btn-agregar px-3 py-1.5 bg-emerald-700 hover:bg-emerald-600 text-white text-xs font-semibold rounded-lg transition-colors" data-uid="<?php echo $usr['id']; ?>">
                    + Agregar
                </button>
                <?php endif; ?>
            </li>
            <?php endforeach; ?>
        </ul>
        <?php endif; ?>
    </div>

</div>
<?php endif; ?>

<script>
const franqId = <?php echo $franquiciadoId ?: 0; ?>;

$(document).ready(function() {

    // Agregar vendedor a la cola
    $(document).on('click', '.btn-agregar', function() {
        const uid = $(this).data('uid');
        $.post('<?php echo APP_URL; ?>/franquiciados/cola/guardar', {
            franquiciado_id: franqId, accion: 'agregar', usuario_id: uid
        }, function(r) {
            if (r.success) { location.reload(); }
            else Swal.fire({ icon: 'error', title: 'Error', text: r.message, background: '#1e293b', color: '#f8fafc' });
        }, 'json');
    });

    // Quitar vendedor de la cola
    $(document).on('click', '.btn-quitar', function() {
        const uid = $(this).data('uid');
        $.post('<?php echo APP_URL; ?>/franquiciados/cola/guardar', {
            franquiciado_id: franqId, accion: 'quitar', usuario_id: uid
        }, function(r) {
            if (r.success) { location.reload(); }
            else Swal.fire({ icon: 'error', title: 'Error', text: r.message, background: '#1e293b', color: '#f8fafc' });
        }, 'json');
    });

    // Guardar orden
    $('#btnGuardarOrden').on('click', function() {
        const orden = [];
        $('#sortableList li').each(function() { orden.push($(this).data('uid')); });
        $.post('<?php echo APP_URL; ?>/franquiciados/cola/guardar', {
            franquiciado_id: franqId, accion: 'reordenar', 'orden[]': orden
        }, function(r) {
            if (r.success) {
                Swal.fire({ toast: true, position: 'top-end', icon: 'success', title: r.message, background: '#1e293b', color: '#f8fafc', showConfirmButton: false, timer: 1500 });
                location.reload();
            }
        }, 'json');
    });

    // Drag & drop con Sortable.js si está disponible, si no se usa HTML5 básico
    const list = document.getElementById('sortableList');
    if (list && window.Sortable) {
        new Sortable(list, { animation: 150, handle: '[data-lucide="grip-vertical"]' });
    }
});
</script>
