<?php
/**
 * Gerenciamento de Usuários - Super Admin
 */
require_once __DIR__ . '/../../../includes/config.php';

if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

$superAdmin = getSuperAdmin();
$pdo = getDB();

// Processar exclusão de usuário
if ($_SERVER["REQUEST_METHOD"] === "POST" && ($_POST["action"] ?? "") === "delete_user") {
    $userId = (int)($_POST["user_id"] ?? 0);
    if ($userId > 0) {
        try {
            // Verificar se não é o próprio usuário
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            header("Location: " . $_SERVER["PHP_SELF"] . "?deleted=1");
            exit;
        } catch (Exception $e) {
            $error = "Erro ao excluir usuário: " . $e->getMessage();
        }
    }
}

// Filtros
$search = $_GET['search'] ?? '';
$roleFilter = $_GET['role'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Query base
$where = "WHERE 1=1";
$params = [];

if ($search) {
    $where .= " AND (u.name LIKE ? OR u.email LIKE ?)";
    $searchParam = "%{$search}%";
    $params[] = $searchParam;
    $params[] = $searchParam;
}

if ($roleFilter) {
    $where .= " AND u.role = ?";
    $params[] = $roleFilter;
}

// Total
$stmtCount = $pdo->prepare("SELECT COUNT(*) FROM users u {$where}");
$stmtCount->execute($params);
$total = $stmtCount->fetchColumn();
$totalPages = ceil($total / $perPage);

// Buscar usuários
$stmt = $pdo->prepare("
    SELECT u.*, s.name as store_name, s.name as store_nome
    FROM users u
    LEFT JOIN stores s ON u.store_id = s.id
    {$where}
    ORDER BY u.created_at DESC
    LIMIT {$perPage} OFFSET {$offset}
");
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Gerenciar Usuários';
$currentPage = 'users';

include __DIR__ . '/../includes/header.php';
?>
    <div class="app-container">
        <?php include __DIR__ . '/../includes/sidebar.php'; ?>

        <main class="main-content">
            <?php include __DIR__ . '/../includes/topbar.php'; ?>

            <div class="content-area">
                <!-- Page Header -->
                <div class="page-header">
                    <div>
                        <h2>Gerenciar Usuários</h2>
                        <p><?= $total ?> usuários cadastrados</p>
                    </div>
                </div>

                <!-- Filters -->
                <div class="panel">
                    <form method="GET" class="flex gap-4 items-center" style="flex-wrap: wrap;">
                        <div style="flex: 1; min-width: 200px;">
                            <label class="form-label">Buscar</label>
                            <div style="position: relative;">
                                <iconify-icon icon="solar:magnifer-bold" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: var(--text-muted);"></iconify-icon>
                                <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" 
                                       placeholder="Nome ou email..."
                                       class="form-input" style="padding-left: 40px;">
                            </div>
                        </div>
                        <div style="width: 160px;">
                            <label class="form-label">Papel</label>
                            <select name="role" class="form-select">
                                <option value="">Todos</option>
                                <option value="admin" <?= $roleFilter === 'admin' ? 'selected' : '' ?>>Admin</option>
                                <option value="owner" <?= $roleFilter === 'owner' ? 'selected' : '' ?>>Dono</option>
                                <option value="employee" <?= $roleFilter === 'employee' ? 'selected' : '' ?>>Funcionário</option>
                                <option value="customer" <?= $roleFilter === 'customer' ? 'selected' : '' ?>>Cliente</option>
                            </select>
                        </div>
                        <div style="padding-top: 24px;">
                            <button type="submit" class="btn btn-primary">
                                <iconify-icon icon="solar:filter-bold"></iconify-icon>
                                Filtrar
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Users Table -->
                <div class="panel" style="padding: 0; overflow: hidden;">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Usuário</th>
                                <th>Loja</th>
                                <th>Papel</th>
                                <th>Status</th>
                                <th>Cadastro</th>
                                <th style="text-align: right;">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users as $user): ?>
                            <tr>
                                <td>
                                    <div class="flex items-center gap-3">
                                        <img src="https://ui-avatars.com/api/?name=<?= urlencode($user['name'] ?? 'U') ?>&background=CCA43B&color=1A1A1A" 
                                             style="width: 40px; height: 40px; border-radius: 50%;">
                                        <div>
                                            <div class="font-medium"><?= htmlspecialchars($user['name'] ?? 'N/A') ?></div>
                                            <div class="text-muted text-sm"><?= htmlspecialchars($user['email'] ?? '-') ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($user['store_id']): ?>
                                    <span class="text-gold"><?= htmlspecialchars($user['store_name'] ?? $user['store_nome'] ?? 'N/A') ?></span>
                                    <?php else: ?>
                                    <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php
                                    $role = $user['role'] ?? 'user';
                                    $roleClass = match($role) {
                                        'admin' => 'text-danger',
                                        'owner' => 'text-gold',
                                        'employee' => 'text-info',
                                        default => 'text-muted'
                                    };
                                    $roleLabel = match($role) {
                                        'admin' => 'Admin',
                                        'owner' => 'Dono',
                                        'employee' => 'Funcionário',
                                        'customer' => 'Cliente',
                                        default => ucfirst($role)
                                    };
                                    ?>
                                    <span class="<?= $roleClass ?> font-medium"><?= $roleLabel ?></span>
                                </td>
                                <td>
                                    <?php 
                                    $isActive = $user['is_active'] ?? $user['status'] ?? true;
                                    if ($isActive): ?>
                                    <span class="status-badge status-active">Ativo</span>
                                    <?php else: ?>
                                    <span class="status-badge status-inactive">Inativo</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-muted"><?= date('d/m/Y', strtotime($user['created_at'] ?? 'now')) ?></td>
                                <td>
                                    <div class="flex gap-2" style="justify-content: flex-end;">
                                        <a href="edit.php?id=<?= $user['id'] ?>" 
                                           class="btn btn-secondary btn-sm" title="Editar">
                                            <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                        </a>
                                        <?php if ($user['store_id']): ?>
                                        <a href="impersonate.php?user_id=<?= $user['id'] ?>" 
                                           class="btn btn-outline btn-sm" title="Acessar como este usuário">
                                            <iconify-icon icon="solar:eye-bold"></iconify-icon>
                                        </a>
                                        <?php endif; ?>
                                        <button type="button" onclick="confirmDelete(<?= $user['id'] ?>, '<?= htmlspecialchars($user['name'] ?? $user['email']) ?>')" 
                                           class="btn btn-danger btn-sm" title="Excluir">
                                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>

                            <?php if (empty($users)): ?>
                            <tr>
                                <td colspan="6" style="text-align: center; padding: 3rem;">
                                    <iconify-icon icon="solar:users-group-rounded-bold" style="font-size: 3rem; color: var(--text-muted); margin-bottom: 1rem;"></iconify-icon>
                                    <p class="text-muted">Nenhum usuário encontrado</p>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                <div class="flex gap-2" style="justify-content: center; margin-top: 1.5rem;">
                    <?php for ($i = 1; $i <= min($totalPages, 10); $i++): ?>
                    <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&role=<?= urlencode($roleFilter) ?>"
                       class="btn <?= $i === $page ? 'btn-primary' : 'btn-secondary' ?> btn-sm">
                        <?= $i ?>
                    </a>
                    <?php endfor; ?>
                </div>
                <?php endif; ?>
            </div>

<!-- Delete Modal -->
<div id="deleteModal" class="modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;align-items:center;justify-content:center;">
    <div class="panel" style="max-width:400px;text-align:center;">
        <iconify-icon icon="solar:trash-bin-trash-bold" style="font-size:3rem;color:var(--danger);"></iconify-icon>
        <h3 style="margin:1rem 0 0.5rem;">Excluir Usuário</h3>
        <p id="deleteMessage" style="color:var(--text-muted);margin-bottom:1.5rem;"></p>
        <form id="deleteForm" method="POST">
            <input type="hidden" name="action" value="delete_user">
            <input type="hidden" name="user_id" id="deleteUserId">
            <div class="flex gap-2" style="justify-content:center;">
                <button type="button" onclick="closeDeleteModal()" class="btn btn-secondary">Cancelar</button>
                <button type="submit" class="btn btn-danger">Excluir</button>
            </div>
        </form>
    </div>
</div>

<script>
function confirmDelete(userId, userName) {
    document.getElementById("deleteUserId").value = userId;
    document.getElementById("deleteMessage").textContent = 'Tem certeza que deseja excluir o usuário "' + userName + '"? Esta ação não pode ser desfeita.';
    document.getElementById("deleteModal").style.display = "flex";
}
function closeDeleteModal() {
    document.getElementById("deleteModal").style.display = "none";
}
</script>
        </main>
    </div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
