<?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" id="connectionsTable">
            <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" onclick="desconectar(<?= $c->conexion_id ?>)">Desconectar</button>
                            <?php else: ?>
                                <button class="btn btn-success btn-xs" onclick="conectar(<?= $c->conexion_id ?>)">Conectar</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function conectar(id){
    $.ajax({
        url: '<?= admin_url('token_connection/conectar/') ?>'+id,
        type: 'POST',
        dataType: 'json',
        success: function(response){
            if(response.status == 'ok'){
                alert('Conectado!\nToken: '+response.token+'\nExpira: '+response.expiracion);
                location.reload();
            } else {
                alert(response.message);
            }
        },
        error: function(xhr){
            alert('Error AJAX: '+xhr.status+' - '+xhr.responseText);
        }
    });
}

function desconectar(id){
    $.ajax({
        url: '<?= admin_url('token_connection/desconectar/') ?>'+id,
        type: 'POST',
        dataType: 'json',
        success: function(response){
            if(response.status == 'ok'){
                alert('Desconectado!');
                location.reload();
            } else {
                alert(response.message);
            }
        },
        error: function(xhr){
            alert('Error AJAX: '+xhr.status+' - '+xhr.responseText);
        }
    });
}
</script>
