<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<div class="box">
    <div class="box-header">
        <h2 class="blue"><i class="fa fa-certificate"></i> Token Connections</h2>
    </div>
    <div class="box-content">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Usuario</th>
                    <th>Token</th>
                    <th>Expiración</th>
                    <th>Acción</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($connections as $c): ?>
                    <tr id="row-<?= $c->conexion_id ?>">
                        <td><?= $c->conexion_id ?></td>
                        <td><?= $c->usuario ?></td>
                        <td><?= $c->token ?: 'No conectado' ?></td>
                        <td><?= $c->expiracion ?: '-' ?></td>
                        <td>
                            <?php if($c->token): ?>
                                <button class="btn btn-danger btn-xs openModal" 
                                        data-id="<?= $c->conexion_id ?>" 
                                        data-action="desconectar">
                                    Desconectar
                                </button>
                            <?php else: ?>
                                <button class="btn btn-success btn-xs openModal" 
                                        data-id="<?= $c->conexion_id ?>" 
                                        data-action="conectar">
                                    Conectar
                                </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Contenedor donde cargaremos el modal -->
<div id="modalContainer"></div>

<script>
$(document).on("click", ".openModal", function(){
    let id     = $(this).data("id");
    let action = $(this).data("action");

    $.ajax({
        url: "<?= admin_url('token_connection/view_modal') ?>",
        type: "POST",
        data: { id: id, action: action },
        success: function(html){
            $("#modalContainer").html(html);
            $("#tokenModal").modal("show");
        },
        error: function(xhr){
            alert("Error cargando modal: " + xhr.status);
        }
    });
});
</script>
