<?php
require_once __DIR__ . '/../includes/session_check.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/activity_logger.php';

// Admin-only access
if ($_SESSION['role'] !== 'admin') {
    header('Location: ../index.php?error=unauthorized');
    exit();
}

// Inicializar variables para el modo edición
$edit_mode = false;
$edit_id = null;
$edit_username = '';
$edit_role = 'user';
$edit_telegram_chat_id = '';

// Handle GET actions for editing
if (isset($_GET['edit'])) {
    $edit_id = $_GET['edit'];
    $stmt = $pdo->prepare("SELECT id, username, role, telegram_chat_id FROM users WHERE id = ?");
    $stmt->execute([$edit_id]);
    $user_to_edit = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user_to_edit) {
        $edit_mode = true;
        $edit_username = $user_to_edit['username'];
        $edit_role = $user_to_edit['role'];
        $edit_telegram_chat_id = $user_to_edit['telegram_chat_id'];
    } else {
        $error = "Usuario no encontrado.";
    }
}

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Action: Create or Update User
    if (isset($_POST['save_user'])) {
        $username = $_POST['username'];
        $role = $_POST['role'];
        $telegram_chat_id = trim($_POST['telegram_chat_id']);
        $is_edit = isset($_POST['edit_id']);

        if (empty($username) || empty($role)) {
            $error = "El nombre de usuario y el rol son obligatorios.";
        } elseif (!empty($telegram_chat_id) && !is_numeric($telegram_chat_id)) {
            $error = "El ID de Chat de Telegram debe ser un número.";
        } else {
            $chat_id_to_save = empty($telegram_chat_id) ? null : $telegram_chat_id;
            try {
                if ($is_edit) {
                    $edit_id = $_POST['edit_id'];
                    $details = 'Admin ' . $_SESSION['username'] . ' updated user: ' . $username . ' (ID: ' . $edit_id . ').';
                    
                    if (!empty($_POST['password'])) {
                        $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
                        $stmt = $pdo->prepare("UPDATE users SET username = ?, password = ?, role = ?, telegram_chat_id = ? WHERE id = ?");
                        $stmt->execute([$username, $hashedPassword, $role, $chat_id_to_save, $edit_id]);
                        $details .= ' Password was changed.';
                    } else {
                        $stmt = $pdo->prepare("UPDATE users SET username = ?, role = ?, telegram_chat_id = ? WHERE id = ?");
                        $stmt->execute([$username, $role, $chat_id_to_save, $edit_id]);
                    }
                    log_activity($_SESSION['user_id'], 'User Updated', $details);
                    header('Location: users.php?success=updated');
                    exit();
                } else {
                    if (empty($_POST['password'])) {
                        $error = "La contraseña es obligatoria para nuevos usuarios.";
                    } else {
                        $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
                        $stmt = $pdo->prepare("INSERT INTO users (username, password, role, telegram_chat_id) VALUES (?, ?, ?, ?)");
                        $stmt->execute([$username, $hashedPassword, $role, $chat_id_to_save]);
                        $new_user_id = $pdo->lastInsertId();
                        log_activity($_SESSION['user_id'], 'User Created', 'Admin ' . $_SESSION['username'] . ' created new user: ' . $username . ' (ID: ' . $new_user_id . ')');
                        header('Location: users.php?success=created');
                        exit();
                    }
                }
            } catch (PDOException $e) {
                $error = ($e->errorInfo[1] == 1062) ? "El nombre de usuario ya existe." : "Error al guardar el usuario: " . $e->getMessage();
                if ($is_edit) {
                    $edit_mode = true;
                    $edit_id = $_POST['edit_id'];
                    $edit_username = $username;
                    $edit_role = $role;
                    $edit_telegram_chat_id = $telegram_chat_id;
                }
            }
        }
    }
    // ... (Otras acciones POST como eliminar, etc. se mantienen aquí)
}

// Fetch all users to display
$users = $pdo->query("SELECT id, username, role, created_at, telegram_chat_id FROM users ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../templates/header.php';
?>

<div class="container-fluid">
    <h1 class="mt-4" data-translate="true">Administrar Usuarios</h1>

    <?php if (isset($error)): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>
    <?php if (isset($_GET['success'])): /* ... Lógica de mensajes de éxito ... */ endif; ?>

    <!-- Create/Edit User Form -->
    <div class="card shadow-sm mb-4">
        <div class="card-header">
            <h5 class="mb-0" data-translate="true"><?= $edit_mode ? 'Editar Usuario' : 'Crear Nuevo Usuario' ?></h5>
        </div>
        <div class="card-body">
            <form action="users.php" method="POST">
                <?php if ($edit_mode): ?>
                    <input type="hidden" name="edit_id" value="<?= $edit_id ?>">
                <?php endif; ?>
                <div class="row align-items-end">
                    <div class="col-md-3 mb-3">
                        <label for="username" class="form-label" data-translate="true">Usuario</label>
                        <input type="text" class="form-control" id="username" name="username" 
                               value="<?= htmlspecialchars($edit_username) ?>" required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label for="password" class="form-label">
                            <span data-translate="true">Contraseña</span> <?php if ($edit_mode): ?><small class="text-muted" data-translate="true">(no cambiar)</small><?php endif; ?>
                        </label>
                        <input type="password" class="form-control" id="password" name="password" <?= !$edit_mode ? 'required' : '' ?>>
                    </div>
                    <div class="col-md-2 mb-3">
                        <label for="role" class="form-label" data-translate="true">Rol</label>
                        <select class="form-select" id="role" name="role" required>
                            <option value="user" <?= ($edit_role === 'user') ? 'selected' : '' ?> data-translate="true">Usuario</option>
                            <option value="admin" <?= ($edit_role === 'admin') ? 'selected' : '' ?> data-translate="true">Admin</option>
                        </select>
                    </div>
                    <div class="col-md-2 mb-3">
                        <label for="telegram_chat_id" class="form-label" data-translate="true">ID Chat Telegram</label>
                        <input type="text" class="form-control" id="telegram_chat_id" name="telegram_chat_id" 
                               value="<?= htmlspecialchars($edit_telegram_chat_id) ?>" placeholder="(Opcional)">
                    </div>
                    <div class="col-md-2 mb-3">
                        <button type="submit" name="save_user" class="btn btn-<?= $edit_mode ? 'success' : 'primary' ?> w-100" data-translate="true">
                            <?= $edit_mode ? 'Actualizar' : 'Crear' ?>
                        </button>
                        <?php if ($edit_mode): ?>
                            <a href="users.php" class="btn btn-outline-secondary w-100 mt-2" data-translate="true">Cancelar</a>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Users List -->
    <div class="card shadow-sm">
        <div class="card-header"><h5 data-translate="true">Lista de Usuarios</h5></div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th data-translate="true">ID</th>
                            <th data-translate="true">Usuario</th>
                            <th data-translate="true">Rol</th>
                            <th data-translate="true">ID Chat Telegram</th>
                            <th data-translate="true">Creado en</th>
                            <th class="text-center" data-translate="true">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                        <tr>
                            <td><?= $user['id'] ?></td>
                            <td><?= htmlspecialchars($user['username']) ?></td>
                            <td><?= ucfirst($user['role']) ?></td>
                            <td>
                                <?php if (!empty($user['telegram_chat_id'])): ?>
                                    <span class="badge bg-info text-dark"><?= htmlspecialchars($user['telegram_chat_id']) ?></span>
                                <?php else: ?>
                                    <span class="badge bg-secondary" data-translate="true">No vinculado</span>
                                <?php endif; ?>
                            </td>
                            <td><?= date('d/m/Y H:i', strtotime($user['created_at'])) ?></td>
                            <td class="text-center">
                                <a href="?edit=<?= $user['id'] ?>#username" class="btn btn-sm btn-primary" title="Editar" data-translate-title="true">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                <!-- Otros botones de acción (modal, eliminar) -->
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Modales y Scripts -->
<?php require_once __DIR__ . '/../templates/footer.php'; ?>
