<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<script>
$(document).ready(function () {
    oTable = $('#ClientesData').dataTable({
        "aaSorting": [[1, "asc"]],
        "aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "<?= lang('all') ?>"]],
        "iDisplayLength": <?= $Settings->rows_per_page ?>,
        'bProcessing': true,
        'bServerSide': true,
        'sAjaxSource': '<?= admin_url('clientes_certificador/getConexiones') ?>',
        'fnServerData': function (sSource, aoData, fnCallback) {
            aoData.push({
                "name": "<?= $this->security->get_csrf_token_name() ?>",
                "value": "<?= $this->security->get_csrf_hash() ?>"
            });
            $.ajax({'dataType': 'json', 'type': 'POST', 'url': sSource, 'data': aoData, 'success': fnCallback});
        },
        'fnRowCallback': function (nRow, aData, iDisplayIndex) {
            nRow.id = aData[0];
            nRow.className = "conexion_details_link";
            return nRow;
        },
        "aoColumns": [
            {"bSortable": false, "mRender": checkbox},
            null,
            null,
            null,
            null,
            null,
            {
                "mRender": function(data, type, row) {
                    return data == 1 ? 'Sí' : 'No';
                }
            },
            {
                "bSortable": false,
                "mRender": function(data, type, row) {

                    let conectado = row[8]; // el backend debe enviar 1 si token activo, 0 si no

                }
            }
        ]
    });
});

var clienteId = null;

// ⭐ FUNCION PARA MOSTRAR MODAL Y CONECTAR AUTOMÁTICAMENTE
function abrirModal(id) {
    clienteId = id;

    $('#resultadoConexion').html('<span class="label label-info">Conectando...</span>');
    $('#modalConectar').modal('show');

    $.ajax({
        url: '<?= admin_url('clientes_certificador/conectar/') ?>' + clienteId,
        type: 'POST',
        dataType: 'json',
        success: function(response){
            if (response.status === 'success') {
                $('#resultadoConexion').html(
                    '<span class="label label-success">¡Conectado correctamente!</span><br>' +
                    'Token: ' + response.token + '<br>' +
                    'Expira: ' + response.expira
                );
                oTable.fnDraw();
            } else {
                $('#resultadoConexion').html(
                    '<span class="label label-danger">Error: ' + response.message + '</span>'
                );
            }
        },
        error: function(xhr, textStatus, errorThrown){
            $('#resultadoConexion').html(
                '<span class="label label-danger">Error AJAX: ' + xhr.status + ' - ' + errorThrown + '</span>'
            );
        }
    });
}

// ⭐ FUNCION PARA DESCONECTAR
function desconectar(id) {
    if (!confirm("¿Seguro que deseas desconectar esta sucursal del certificador?")) return;

    $.ajax({
        url: '<?= admin_url('clientes_certificador/desconectar/') ?>' + id,
        type: 'POST',
        dataType: 'json',
        success: function(response){
            if (response.status === 'success') {
                alert("Conexión desconectada.");
                oTable.fnDraw();
            } else {
                alert("Error: " + response.message);
            }
        },
        error: function(xhr, textStatus, errorThrown){
            alert("Error AJAX: " + xhr.status + " - " + errorThrown);
        }
    });
}
</script>

<!-- 🔹 MODAL -->
<div class="modal fade" id="modalConectar" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-body text-center">
                <h4><i class="fa fa-cog fa-spin"></i> Conectando...</h4>
                <p>Estamos generando el token y conectando al certificador.</p>
                <div id="resultadoConexion"></div>
            </div>
            <div class="modal-footer text-center">
                <button class="btn btn-default" data-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>

<?php if ($Owner || $GP['bulk_actions']) {
    echo admin_form_open('clientes_certificador/conexion_actions', 'id="action-form"');
} ?>

<div class="box">
    <div class="box-header">
        <h2 class="blue"><i class="fa-fw fa fa-certificate"></i><?= lang('clientes_certificador'); ?></h2>
        <div class="box-icon">
            <ul class="btn-tasks">
                <li class="dropdown">
                    <a data-toggle="dropdown" class="dropdown-toggle" href="#">
                        <i class="icon fa fa-tasks tip" data-placement="left" title="<?= lang('actions') ?>"></i>
                    </a>
                    <ul class="dropdown-menu pull-right tasks-menus" role="menu">
                        <li>
                            <a href="<?= admin_url('clientes_certificador/add'); ?>" data-toggle="modal" data-target="#myModal" id="add">
                                <i class="fa fa-plus-circle"></i> <?= lang('add_conexion'); ?>
                            </a>
                        </li>
                        <li>
                            <a href="#" id="excel" data-action="export_excel">
                                <i class="fa fa-file-excel-o"></i> <?= lang('export_to_excel') ?>
                            </a>
                        </li>
                        <li class="divider"></li>
                        <li>
                            <a href="#" class="bpo" title="<b><?= $this->lang->line('delete_conexiones') ?></b>"
                               data-content="<p><?= lang('r_u_sure') ?></p>
                               <button type='button' class='btn btn-danger' id='delete' data-action='delete'><?= lang('i_m_sure') ?></button> 
                               <button class='btn bpo-close'><?= lang('no') ?></button>" data-html="true" data-placement="left">
                                <i class="fa fa-trash-o"></i> <?= lang('delete_conexiones') ?>
                            </a>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>

    <div class="box-content">
        <div class="row">
            <div class="col-lg-12">
                <p class="introtext"><?= lang('list_results'); ?></p>
                <div class="table-responsive">
                    <table id="ClientesData" cellpadding="0" cellspacing="0" border="0"
                           class="table table-bordered table-condensed table-hover table-striped">
                        <thead>
                        <tr class="primary">
                            <th style="min-width:30px; width: 30px; text-align: center;">
                                <input class="checkbox checkth" type="checkbox" name="check"/>
                            </th>
                            <th><?= lang('sucursal'); ?></th>
                            <th><?= lang('certificador'); ?></th>
                            <th><?= lang('nit'); ?></th>
                            <th><?= lang('usuario'); ?></th>
                            <th><?= lang('contrasena'); ?></th>
                            <th><?= lang('activo'); ?></th>
                            <th style="min-width:105px; text-align:center;"><?= lang('actions'); ?></th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <td colspan="8" class="dataTables_empty"><?= lang('loading_data_from_server') ?></td>
                        </tr>
                        </tbody>
                        <tfoot class="dtFilter"></tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
