<?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) {
                    // 🚀 Aquí agregamos el botón que abre el modal
                    return '<button class="btn btn-xs btn-primary" data-toggle="modal" data-target="#modalConectar" onclick="abrirModal('+row[0]+')"><i class="fa fa-plug"></i> Conectar</button>';
                }
            }
        ]
    }).dtFilter([
        {column_number: 1, filter_default_label: "[<?=lang('sucursal');?>]", filter_type: "text", data: []},
        {column_number: 2, filter_default_label: "[<?=lang('certificador');?>]", filter_type: "text", data: []},
        {column_number: 3, filter_default_label: "[<?=lang('nit');?>]", filter_type: "text", data: []},
        {column_number: 4, filter_default_label: "[<?=lang('usuario');?>]", filter_type: "text", data: []},
        {column_number: 5, filter_default_label: "[<?=lang('contrasena');?>]", filter_type: "text", data: []},
        {column_number: 6, filter_default_label: "[<?=lang('activo');?>]", filter_type: "text", data: []},
    ], "footer");
});

var clienteId = null;

// 🚀 Abrir modal y ejecutar conexión automática
function abrirModal(id) {
    clienteId = id;

    // Cuando el modal ya esté visible, ejecutar la conexión
    $('#modalConectar').on('shown.bs.modal', function () {
        $.ajax({
            url: '<?= admin_url('Token_connection/conectar/') ?>' + clienteId,
            type: 'POST',
            dataType: 'json',
            success: function(response){
                if (response.status === 'success') {
                    $('#resultadoConexion').html(
                        '<span class="label label-success">¡Conectado!</span><br>' +
                        'Token: ' + response.token + '<br>' +
                        'Expira: ' + response.expira
                    );
                } 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>'
                );
            }
        });
    });

    // limpiar evento cuando se cierre
    $('#modalConectar').on('hidden.bs.modal', function () {
        $('#resultadoConexion').html('');
        $('#modalConectar').off('shown.bs.modal');
    });

    // Abrir modal
    $('#modalConectar').modal('show');
}
</script>

<!-- 🔹 Modal de conexión -->
<div class="modal fade" id="modalConectar" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="modalLabel">Conectar con Certificador</h4>
      </div>
      <div class="modal-body">
        <div id="resultadoConexion" class="text-center">
          <span class="label label-info">Conectando...</span>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
      </div>
    </div>
  </div>
</div>

</script>

<?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>

<!-- 🚀 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>
    </div>
</div>
