<?php
// admin/users_list.php

require_once('../includes/admin_check.php');
$page_title = 'Admin - Lista de Usuarios';

require_once('../config/database.php');
require_once('../includes/functions.php'); 

// --- Lógica de Búsqueda y Filtro ---
$search_username = trim(filter_input(INPUT_GET, 'search_username', FILTER_SANITIZE_SPECIAL_CHARS));
$search_fullname = trim(filter_input(INPUT_GET, 'search_fullname', FILTER_SANITIZE_SPECIAL_CHARS));
$search_employee_id = trim(filter_input(INPUT_GET, 'search_employee_id', FILTER_SANITIZE_SPECIAL_CHARS));

$where_clauses = [];
$bind_params = [];
$param_types = '';
$search_params_for_url = ''; // Para los enlaces de paginación

if (!empty($search_username)) {
    $where_clauses[] = "username LIKE ?";
    $bind_params[] = "%" . $search_username . "%";
    $param_types .= 's';
    $search_params_for_url .= '&search_username=' . urlencode($search_username);
}
if (!empty($search_fullname)) {
    $where_clauses[] = "full_name LIKE ?";
    $bind_params[] = "%" . $search_fullname . "%";
    $param_types .= 's';
    $search_params_for_url .= '&search_fullname=' . urlencode($search_fullname);
}
if (!empty($search_employee_id)) {
    $where_clauses[] = "employee_id = ?";
    $bind_params[] = $search_employee_id;
    $param_types .= 's';
    $search_params_for_url .= '&search_employee_id=' . urlencode($search_employee_id);
}

$where_sql = '';
if (!empty($where_clauses)) {
    $where_sql = " WHERE " . implode(" AND ", $where_clauses);
}

// --- Lógica de Paginación ---
$items_per_page = 10; 
$total_users = 0;

$sql_total_users = "SELECT COUNT(id) as total FROM user" . $where_sql;
$stmt_total = $conn->prepare($sql_total_users);
if ($stmt_total) {
    if (!empty($bind_params)) {
        $stmt_total->bind_param($param_types, ...$bind_params);
    }
    $stmt_total->execute();
    $result_total_users = $stmt_total->get_result();
    $total_users_row = $result_total_users->fetch_assoc();
    $total_users = $total_users_row['total'] ?? 0;
    $stmt_total->close();
} else {
    error_log("Error preparando la consulta de conteo de usuarios: " . $conn->error);
}

$total_pages = $total_users > 0 ? ceil($total_users / $items_per_page) : 1;

$current_page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]);
if ($current_page === false || $current_page < 1 || ($current_page > $total_pages && $total_pages > 0) ) {
    $current_page = 1; 
}
$offset = ($current_page - 1) * $items_per_page;

$users = [];
$sql_select = "SELECT id, username, employee_id, is_admin, is_supervisor, full_name, email, force_password_change, initial_access_sent 
               FROM user" . $where_sql . " ORDER BY username LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql_select);
if ($stmt) {
    $final_params = $bind_params;
    $final_params[] = $items_per_page;
    $final_params[] = $offset;
    $final_param_types = $param_types . 'ii';

    $stmt->bind_param($final_param_types, ...$final_params);
    
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result) {
        while($row = $result->fetch_assoc()) {
            $users[] = $row;
        }
    }
    $stmt->close();
} else {
    error_log("Error preparando la consulta para obtener lista de usuarios: " . $conn->error);
}

$csrf_token_actions = generate_csrf_token();
require_once('../includes/header.php'); 
?>
<main class="container main-container-flex-column">

    <h2>Administración de Usuarios</h2>

    <?php // Mostrar mensajes de sesión
    if (isset($_SESSION['success_message'])): ?>
        <p class="success"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?></p>
    <?php endif; ?>
    <?php if (isset($_SESSION['error_message'])): ?>
        <p class="error"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?></p>
    <?php endif; ?>
    <?php if (isset($_SESSION['info_message'])): ?>
        <p class="info-message"><?php echo $_SESSION['info_message']; unset($_SESSION['info_message']); ?></p>
    <?php endif; ?>
     <?php if (isset($_SESSION['reset_warning_message'])): ?>
        <p class="warning-message">
            <?php echo $_SESSION['reset_warning_message']; unset($_SESSION['reset_warning_message']); ?>
        </p>
    <?php endif; ?>

    <div class="filter-container" style="margin-bottom: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 6px;">
        <form method="GET" action="users_list.php" class="filter-form">
            <fieldset>
                <legend style="font-size: 1.1em; font-weight: 600;">Buscar Usuarios</legend>
                <div class="grid">
                    <div>
                        <label for="search_username">Por Username:</label>
                        <input type="text" id="search_username" name="search_username" value="<?php echo htmlspecialchars($search_username); ?>" placeholder="Contiene...">
                    </div>
                    <div>
                        <label for="search_fullname">Por Nombre Completo:</label>
                        <input type="text" id="search_fullname" name="search_fullname" value="<?php echo htmlspecialchars($search_fullname); ?>" placeholder="Contiene...">
                    </div>
                    <div>
                        <label for="search_employee_id">Por ID Empleado:</label>
                        <input type="text" id="search_employee_id" name="search_employee_id" value="<?php echo htmlspecialchars($search_employee_id); ?>" placeholder="ID exacto...">
                    </div>
                    <div style="align-self: flex-end;">
                        <button type="submit" class="button">Buscar</button>
                        <a href="users_list.php" class="button button-outline" style="margin-left: 5px;">Limpiar Búsqueda</a>
                    </div>
                </div>
            </fieldset>
        </form>
    </div>

    <div class="admin-actions" style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
        <div>
            <a href="user_form.php" class="button">Añadir Nuevo Usuario</a>
            <a href="bulk_upload.php" class="button button-secondary">Carga Masiva Usuarios</a>
            <a href="upload_receipts.php" class="button button-secondary">Cargar Recibos</a>
        </div>
        <div>
            <form action="bulk_initial_access.php" method="POST" style="display: inline;" onsubmit="return confirm('¿Estás seguro de que quieres generar NUEVAS contraseñas y enviar los ACCESOS INICIALES por correo a todos los usuarios elegibles en ESTA PÁGINA?');">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token_actions); ?>">
                <input type="hidden" name="current_page" value="<?php echo $current_page; ?>">
                <input type="hidden" name="items_per_page" value="<?php echo $items_per_page; ?>">
                <button type="submit" class="button button-outline" title="Envía accesos a usuarios de esta página que no los hayan recibido y tengan email.">Enviar Accesos Iniciales (Pág. Actual)</button>
            </form>
            <a href="delete_all_users.php" class="button button-outline button-danger" style="margin-left: 10px;" onclick="return confirm('¡ADVERTENCIA EXTREMA!\n\nEstás a punto de eliminar a TODOS los usuarios que NO SON administradores.\n\nESTA ACCIÓN ES IRREVERSIBLE.');">Eliminar No-Admins</a>
        </div>
    </div>

    <div class="table-scroll-container">
        <table class="file-table"> 
            <thead>
                <tr>
                    <th>ID</th><th>Username</th><th>Nombre Completo</th><th>Email</th><th>ID Empleado</th>
                    <th>Admin</th><th>Supervisor</th><th>Forzar Cambio Pass</th><th>Accesos Enviados</th>
                    <th>Acciones</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($users)): ?>
                    <tr><td colspan="10" style="text-align:center; padding: 20px;">No se encontraron usuarios que coincidan con los criterios de búsqueda.</td></tr>
                <?php else: ?>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td><?php echo $user['id']; ?></td>
                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                        <td><?php echo htmlspecialchars($user['full_name'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($user['email'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars($user['employee_id']); ?></td>
                        <td><?php echo $user['is_admin'] ? 'Sí' : 'No'; ?></td>
                        <td><?php echo $user['is_supervisor'] ? 'Sí' : 'No'; ?></td>
                        <td><?php echo $user['force_password_change'] ? '<strong style="color:orange;">Sí</strong>' : 'No'; ?></td>
                        <td><?php echo $user['initial_access_sent'] ? '<span style="color:green;">Sí</span>' : '<span style="color:red;">No</span>'; ?></td>
                        <td style="white-space: nowrap;">
                            <a href="user_form.php?id=<?php echo $user['id']; ?>" class="button button-small">Editar</a>
                            <?php 
                                $send_access_text = $user['initial_access_sent'] ? 'Reenviar/Resetear Accesos' : 'Enviar Accesos Iniciales';
                                $confirm_message = $user['initial_access_sent'] 
                                    ? '¿Estás seguro de que quieres RESETEAR y REENVIAR los accesos por correo a ' . htmlspecialchars(addslashes($user['username'])) . '?'
                                    : '¿Estás seguro de que quieres ENVIAR los ACCESOS INICIALES por correo a ' . htmlspecialchars(addslashes($user['username'])) . '?';
                            ?>
                            <form action="reset_send_access.php" method="POST" style="display: inline-block; margin-left: 5px;" onsubmit="return confirm('<?php echo $confirm_message; ?>');">
                                <input type="hidden" name="user_id_to_reset" value="<?php echo $user['id']; ?>">
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token_actions); ?>">
                                <button type="submit" class="button button-small <?php echo $user['initial_access_sent'] ? 'button-outline' : ''; ?>" 
                                        <?php echo empty($user['email']) ? 'disabled title="Este usuario no tiene un email configurado para enviar accesos."' : ''; ?>>
                                    <?php echo $send_access_text; ?>
                                </button>
                            </form>
                            <form action="user_delete.php" method="POST" style="display: inline-block; margin-left: 5px;" onsubmit="return confirm('ADVERTENCIA:\n¿Estás REALMENTE seguro de que quieres eliminar al usuario \'<?php echo htmlspecialchars(addslashes($user['username'])); ?>\'?\n¡Esta acción no se puede deshacer!');">
                                <input type="hidden" name="id" value="<?php echo $user['id']; ?>">
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token_actions); ?>">
                                <button type="submit" class="button button-outline button-small button-danger-outline">Eliminar</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($total_pages > 1): ?>
    <nav class="pagination-nav" style="margin-top: 20px; text-align: center;">
        <ul style="list-style: none; padding: 0; margin: 0; display: inline-flex; gap: 5px; align-items: center;">
            <?php if ($current_page > 1): ?><li><a href="?page=<?php echo $current_page - 1; ?><?php echo $search_params_for_url; ?>" class="button button-outline button-small">&laquo; Anterior</a></li><?php else: ?><li><span class="button button-outline button-small disabled">&laquo; Anterior</span></li><?php endif; ?>
            <?php 
                $num_links_mostrados = 5; 
                $start_link = max(1, $current_page - floor($num_links_mostrados / 2));
                $end_link = min($total_pages, $start_link + $num_links_mostrados - 1);
                if ($end_link - $start_link + 1 < $num_links_mostrados && $start_link > 1) { $start_link = max(1, $end_link - $num_links_mostrados + 1); }
            ?>
            <?php if ($start_link > 1): ?><li><a href="?page=1<?php echo $search_params_for_url; ?>" class="button button-outline button-small">1</a></li><?php if ($start_link > 2): ?><li><span style="padding: 0 5px;">...</span></li><?php endif; ?><?php endif; ?>
            <?php for ($i = $start_link; $i <= $end_link; $i++): ?><li><a href="?page=<?php echo $i; ?><?php echo $search_params_for_url; ?>" class="button button-small <?php echo ($i == $current_page) ? '' : 'button-outline'; ?>"><?php echo $i; ?></a></li><?php endfor; ?>
            <?php if ($end_link < $total_pages): ?><?php if ($end_link < $total_pages - 1): ?><li><span style="padding: 0 5px;">...</span></li><?php endif; ?><li><a href="?page=<?php echo $total_pages; ?><?php echo $search_params_for_url; ?>" class="button button-outline button-small"><?php echo $total_pages; ?></a></li><?php endif; ?>
            <?php if ($current_page < $total_pages): ?><li><a href="?page=<?php echo $current_page + 1; ?><?php echo $search_params_for_url; ?>" class="button button-outline button-small">Siguiente &raquo;</a></li><?php else: ?><li><span class="button button-outline button-small disabled">Siguiente &raquo;</span></li><?php endif; ?>
        </ul>
    </nav>
    <?php endif; ?>
</main>
<?php
require_once('../includes/footer.php'); 
if(isset($conn) && $conn instanceof mysqli) $conn->close(); 
?>