<?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 (nombre LIKE '%".$q."%' OR apellido LIKE '%".$q."%')";
    }
    if (!empty($est)){
        $where .= " AND tienda='".$est."'";
    }

    $sql="SELECT * FROM nomina $where ORDER BY tienda ASC";
    $count_query = mysqli_query($con, "SELECT count(*) AS numrows FROM nomina $where");
    
    include 'pagination.php';
    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = 40;
    $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 = './empleados.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>Sueldo Diario</th>
                    <th class='text-right'>Acciones</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if ($numrows > 0){
                    $j = $offset;
                    while ($row = mysqli_fetch_array($query)){ 
                        $j++;
                        $empleado_id = $row['id_nomina'];
                        $fullname = $row['nombre']." ".$row["apellido"];
                        $sueldo = $row['sueldo'];
                        $cargo = strtoupper($row['cargo']);
                        $estado_id = $row['tienda']; 
                         
                        // Etiqueta de color según el ROL
                        $label_class = ($cargo == "GERENCIA" || $cargo == "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['nombre'];?>" id="nombres<?php echo $empleado_id;?>">
                    <input type="hidden" value="<?php echo $row['apellido'];?>" id="apellidos<?php echo $empleado_id;?>">
                    <input type="hidden" value="<?php echo $cargo;?>" id="rol<?php echo $empleado_id;?>">
                    <input type="hidden" value="<?php echo $sueldo;?>" id="sueldo<?php echo $empleado_id;?>">
                    <input type="hidden" value="<?php echo $row['cedula'];?>" id="cedula<?php echo $empleado_id;?>">
                    <input type="hidden" value="<?php echo $row['fecha_ingreso'];?>" id="fecha_ingreso<?php echo $empleado_id;?>">
                    <input type="hidden" value="<?php echo $estado_id;?>" id="estado_id<?php echo $empleado_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 $cargo; ?></span></td>
                        <td><code><?php echo $sueldo; ?></code></td>
                        <td class='text-right'>
                            <div class="btn-group">
                                <button class='btn btn-info btn-sm' title='Descargar constancia' onclick="window.open('pdf/constancia_empleado.php?id=<?php echo $empleado_id; ?>','_blank');"><i class="glyphicon glyphicon-download-alt"></i></button>
                                <button class='btn btn-default btn-sm' title='Editar' onclick="obtener_datos('<?php echo $empleado_id; ?>');" data-toggle="modal" data-target="#myModalempleado2"><i class="glyphicon glyphicon-edit"></i></button>
                                <button class='btn btn-danger btn-sm' title='Eliminar' onclick="eliminar('<?php echo $empleado_id; ?>')"><i class="glyphicon glyphicon-trash"></i></button>
                            </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 } ?>