<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/helpers.php';

check_role('administrador');

$user = get_logged_in_user();

$page_title = 'Administrador de Usuarios';

// Handle search and pagination parameters
$search = sanitize_get('search', 'string', ['max_length' => 100]);
$career_filter = sanitize_get('career', 'int');
$page = sanitize_get('page', 'int', ['min' => 1]) ?: 1;
$per_page = 10; // Users per page
$offset = ($page - 1) * $per_page;

// Get careers for filter dropdown
$careers_stmt = $pdo->query("SELECT id, name FROM careers ORDER BY name");
$careers = $careers_stmt->fetchAll(PDO::FETCH_ASSOC);

// Build search query
$search_condition = '';
$params = [];
if (!empty($search)) {
    $search_condition = " AND (u.username LIKE :search OR u.email LIKE :search OR u.first_name LIKE :search OR u.last_name LIKE :search OR r.name LIKE :search)";
    $params[':search'] = '%' . $search . '%';
}

if (!empty($career_filter)) {
    $search_condition .= " AND u.id IN (SELECT user_id FROM students WHERE career_id = :career_id)";
    $params[':career_id'] = $career_filter;
}

// Get total count for pagination
$count_query = "SELECT COUNT(*) as total FROM users u JOIN roles r ON u.role_id = r.id WHERE u.deleted_at IS NULL" . $search_condition;
$count_stmt = $pdo->prepare($count_query);
$count_stmt->execute($params);
$total_users = $count_stmt->fetch()['total'];
$total_pages = ceil($total_users / $per_page);

// Get users with pagination and search
$query = "SELECT u.id, u.username, u.email, r.name as role, u.first_name, u.last_name, u.created_at
          FROM users u
          JOIN roles r ON u.role_id = r.id
          WHERE u.deleted_at IS NULL" . $search_condition . "
          ORDER BY u.created_at DESC
          LIMIT :limit OFFSET :offset";

$stmt = $pdo->prepare($query);
$stmt->bindValue(':limit', $per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();

$content = '
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Usuarios</h3>
                <div class="card-tools">
                    <div class="btn-group">
                        <a href="' . route_url('admin_add_user') . '" class="btn btn-primary btn-sm rounded-pill px-3"><i class="fas fa-plus"></i> Agregar Usuario</a>
                        <a href="export-users.php?format=excel" class="btn btn-success btn-sm rounded-pill px-3"><i class="fas fa-file-excel"></i> Exportar a Excel</a>
                        <a href="export-users.php?format=pdf" class="btn btn-danger btn-sm rounded-pill px-3"><i class="fas fa-file-pdf"></i> Exportar a PDF</a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <!-- Search and Filter Form -->
                <form method="GET" class="mb-3">
                    <div class="row g-3">
                        <div class="col-md-5">
                            <label for="search" class="form-label fw-bold">Buscar Usuario</label>
                            <div class="input-group">
                                <input type="text" name="search" id="search" class="form-control" placeholder="Username, email, nombre, apellido o rol..." value="' . htmlspecialchars($search ?? '') . '">
                                <button type="submit" class="btn btn-outline-secondary">
                                    <i class="fas fa-search"></i> Buscar
                                </button>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label for="career" class="form-label fw-bold">Filtrar por Programas</label>
                            <select name="career" id="career" class="form-select" onchange="this.form.submit()">
                                <option value="">Seleccione ...</option>';
foreach ($careers as $career) {
    $selected = ($career_filter == $career['id']) ? ' selected' : '';
    $content .= '<option value="' . $career['id'] . '"' . $selected . '>' . htmlspecialchars($career['name']) . '</option>';
}
$content .= '
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <div class="d-flex gap-2 w-100">
                                ' . ((!empty($search) || !empty($career_filter)) ? '<a href="users.php" class="btn btn-outline-danger flex-fill"><i class="fas fa-times"></i> Limpiar Filtros</a>' : '') . '
                                <div class="text-end flex-fill">
                                    <small class="text-muted fw-bold">Total: ' . $total_users . ' usuario' . ($total_users != 1 ? 's' : '') . '</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-bordered table-striped no-datatable">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Username</th>
                                <th>Email</th>
                                <th>Rol</th>
                                <th>Nombre Completo</th>
                                <th>Fecha de Registro</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>';

while ($row = $stmt->fetch()) {
    $full_name = htmlspecialchars($row['first_name'] . ' ' . $row['last_name']);
    $content .= '<tr>
        <td>' . $row['id'] . '</td>
        <td>' . htmlspecialchars($row['username']) . '</td>
        <td>' . htmlspecialchars($row['email']) . '</td>
        <td>' . ucfirst($row['role']) . '</td>
        <td>' . $full_name . '</td>
        <td>' . date('d/m/Y', strtotime($row['created_at'])) . '</td>
        <td>
            <a href="view-user.php?id=' . $row['id'] . '" class="btn btn-info btn-sm"><i class="fas fa-eye"></i> </a>
            <a href="edit-user.php?id=' . $row['id'] . '" class="btn btn-warning btn-sm"><i class="fas fa-edit"></i> </a>
            <a href="change-password.php?id=' . $row['id'] . '" class="btn btn-secondary btn-sm"><i class="fas fa-key"></i> </a>
            <a href="delete-user.php?id=' . $row['id'] . '" class="btn btn-danger btn-sm" onclick="return confirm(\'Estás seguro que deseas eliminar este usuario?\')"><i class="fas fa-trash"></i> </a>
        </td>
    </tr>';
}

$content .= '</tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div class="d-flex justify-content-between align-items-center mt-3">
                    <div class="text-muted">
                        Mostrando ' . ($offset + 1) . ' a ' . min($offset + $per_page, $total_users) . ' de ' . $total_users . ' usuarios
                    </div>
                    <nav aria-label="User pagination">
                        <ul class="pagination pagination-sm mb-0">';

// Build URL parameters for pagination
$url_params = [];
if (!empty($search)) $url_params[] = 'search=' . urlencode($search);
if (!empty($career_filter)) $url_params[] = 'career=' . $career_filter;
$url_params_str = !empty($url_params) ? implode('&', $url_params) . '&' : '';

// Previous button
if ($page > 1) {
    $prev_url = 'users.php?' . $url_params_str . 'page=' . ($page - 1);
    $content .= '<li class="page-item"><a class="page-link" href="' . $prev_url . '">&laquo;</a></li>';
} else {
    $content .= '<li class="page-item disabled"><span class="page-link">&laquo;</span></li>';
}

// Page numbers
$start_page = max(1, $page - 2);
$end_page = min($total_pages, $page + 2);

for ($i = $start_page; $i <= $end_page; $i++) {
    $page_url = 'users.php?' . $url_params_str . 'page=' . $i;
    $active_class = ($i == $page) ? ' active' : '';
    $content .= '<li class="page-item' . $active_class . '"><a class="page-link" href="' . $page_url . '">' . $i . '</a></li>';
}

// Next button
if ($page < $total_pages) {
    $next_url = 'users.php?' . $url_params_str . 'page=' . ($page + 1);
    $content .= '<li class="page-item"><a class="page-link" href="' . $next_url . '">&raquo;</a></li>';
} else {
    $content .= '<li class="page-item disabled"><span class="page-link">&raquo;</span></li>';
}

$content .= '
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>';

include BASE_PATH . '/includes/layout.php';
?>