<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once ("../config/db.php");
require_once ("../config/conexion.php");
include('is_logged.php');

$action = (isset($_REQUEST['action']) && $_REQUEST['action'] != NULL) ? $_REQUEST['action'] : '';
if($action == 'ajax'){
    $q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
    $est = mysqli_real_escape_string($con,(strip_tags($_REQUEST['est'], ENT_QUOTES)));

    $where = "WHERE 1=1";
    if (!empty($q)){
        $where .= " AND (firstname LIKE '%".$q."%' OR lastname LIKE '%".$q."%')";
    }
    if (!empty($est)){
        $where .= " AND estado='".$est."'";
    }

    $sql="SELECT * FROM users $where";
    $count_query = mysqli_query($con, "SELECT count(*) AS numrows FROM users $where");
    
    include 'pagination.php';
    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = 10;
    $adjacents = 4;
    $offset = ($page - 1) * $per_page;
    $row_count = mysqli_fetch_array($count_query);
    $numrows = $row_count['numrows'];
    $total_pages = ceil($numrows/$per_page);
    $reload = './usuarios.php';
    
    $sql.=" LIMIT $offset,$per_page";
    $query = mysqli_query($con, $sql);
?>
    <div class="table-responsive">
        <table class="table table-hover" style="border-bottom: 1px solid #eee;">
            <thead>
                <tr class="info">
                    <th>#</th>
                    <th>Sucursal</th>
                    <th>Nombre Completo</th>
                    <th class="text-center">Rol</th>
                    <th>Usuario</th>
                    <th>Email</th>
                    <th class='text-right'>Acciones</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if ($numrows > 0){
                    $j = $offset;
                    while ($row = mysqli_fetch_array($query)){ 
                        $j++;
                        $user_id = $row['user_id'];
                        $fullname = $row['firstname']." ".$row["lastname"];
                        $user_name = $row['user_name'];
                        $rol = strtoupper($row['ROL']);
                        $estado_id = $row['estado']; 
                        $user_email = $row['user_email'];
                        $bloqueado = $row['intentos'];
                        
                        // Etiqueta de color según el ROL
                        $label_class = ($rol == "GERENCIA" || $rol == "ADMINISTRADOR") ? "label-danger" : "label-info";

                        $tienda_nombre = "Sede Central";
                        if (!empty($estado_id)){
                            $q_t = mysqli_query($con, "SELECT nombre FROM tiendas WHERE id_tienda='$estado_id'");
                            if($r_t = mysqli_fetch_array($q_t)){ $tienda_nombre = $r_t['nombre']; }
                        }
                ?>
                    <input type="hidden" value="<?php echo $row['firstname'];?>" id="nombres<?php echo $user_id;?>">
                    <input type="hidden" value="<?php echo $row['lastname'];?>" id="apellidos<?php echo $user_id;?>">
                    <input type="hidden" value="<?php echo $row['ROL'];?>" id="rol<?php echo $user_id;?>">
                    <input type="hidden" value="<?php echo $user_name;?>" id="usuario<?php echo $user_id;?>">
                    <input type="hidden" value="<?php echo $user_email;?>" id="email<?php echo $user_id;?>">
                    <input type="hidden" value="<?php echo $estado_id;?>" id="estado_id<?php echo $user_id;?>">
                    <input type="hidden" value="<?php echo $bloqueado;?>" id="intentos<?php echo $user_id;?>">

                    <tr>
                        <td><span class="badge"><?php echo $j; ?></span></td>
                        <td><i class="glyphicon glyphicon-map-marker text-muted"></i> <?php echo $tienda_nombre; ?></td>
                        <td><strong><?php echo $fullname; ?></strong></td>
                        <td class="text-center"><span class="label <?php echo $label_class; ?>"><?php echo $rol; ?></span></td>
                        <td><code><?php echo $user_name; ?></code></td>
                        <td><small><?php echo $user_email; ?></small></td>
                        <td class='text-right'>
                            <div class="btn-group">
                                <button class='btn btn-default btn-sm' title='Editar' onclick="obtener_datos('<?php echo $user_id; ?>');" data-toggle="modal" data-target="#myModal2"><i class="glyphicon glyphicon-edit"></i></button>
                                
                                <?php if($_SESSION['rol']=="gerencia"){ ?>
                                <button class='btn btn-default btn-sm' title='Seguridad' onclick="get_user_id('<?php echo $user_id;?>');" data-toggle="modal" data-target="#myModal_cla"><i class="glyphicon glyphicon-lock"></i></button>
                                <?php } ?>

                                <button class='btn btn-danger btn-sm' title='Eliminar' onclick="eliminar('<?php echo $user_id; ?>')"><i class="glyphicon glyphicon-trash"></i></button>

                                <?php if ($bloqueado == 1) { ?>
                                    <button class='btn btn-success btn-sm' title='Desbloquear usuario' onclick="toggle_bloqueo('<?php echo $user_id; ?>')"><i class="glyphicon glyphicon-ok"></i></button>
                                <?php } else { ?>
                                    <button class='btn btn-warning btn-sm' title='Bloquear usuario' onclick="toggle_bloqueo('<?php echo $user_id; ?>')"><i class="glyphicon glyphicon-ban-circle"></i></button>
                                <?php } ?>
                            </div>
                        </td>
                    </tr>
                <?php } ?>
                <?php } else { ?>
                    <tr><td colspan="7" class="text-center">No se encontraron colaboradores en esta búsqueda.</td></tr>
                <?php } ?>
            </tbody>
        </table>
        
        <div class="text-right">
            <?php echo paginate($reload, $page, $total_pages, $adjacents);?>
        </div>
    </div>
<?php } ?>