<?php
session_start();
require_once 'db/config.php';

// Check if user is logged in and is an Administrador
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'Administrador') {
    header('Location: login.php');
    exit;
}

$message = '';
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}

// Handle form submission for creating a new user
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_user'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $role = $_POST['role'];
    $nombre_asesor = trim($_POST['nombre_asesor']);

    if (empty($username) || empty($password) || empty($role)) {
        $_SESSION['message'] = '<div class="alert alert-danger">Todos los campos son obligatorios.</div>';
    } else {
        try {
            $db = db();
            // Check if username already exists
            $stmt = $db->prepare("SELECT id FROM users WHERE username = :username");
            $stmt->bindParam(':username', $username);
            $stmt->execute();

            if ($stmt->rowCount() > 0) {
                $_SESSION['message'] = '<div class="alert alert-danger">El nombre de usuario ya existe.</div>';
            } else {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $db->prepare("INSERT INTO users (username, password, role, nombre_asesor) VALUES (:username, :password, :role, :nombre_asesor)");
                $stmt->bindParam(':username', $username);
                $stmt->bindParam(':password', $hashed_password);
                $stmt->bindParam(':role', $role);
                $stmt->bindParam(':nombre_asesor', $nombre_asesor);
                
                if ($stmt->execute()) {
                    $_SESSION['message'] = '<div class="alert alert-success">Usuario creado con éxito.</div>';
                } else {
                    $_SESSION['message'] = '<div class="alert alert-danger">Error al crear el usuario.</div>';
                }
            }
        } catch (PDOException $e) {
            $_SESSION['message'] = '<div class="alert alert-danger">Error de base de datos: ' . $e->getMessage() . '</div>';
        }
    }
    header('Location: manage_users.php');
    exit;
}

// Handle form submission for updating a user
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_user'])) {
    $user_id = $_POST['user_id'];
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $role = $_POST['role'];
    $nombre_asesor = trim($_POST['nombre_asesor']);

    if (empty($user_id) || empty($username) || empty($role)) {
        $message = '<div class="alert alert-danger">Error: Faltan datos para actualizar.</div>';
    } else {
        try {
            $db = db();
            // Check if username already exists for another user
            $stmt = $db->prepare("SELECT id FROM users WHERE username = :username AND id != :id");
            $stmt->bindParam(':username', $username);
            $stmt->bindParam(':id', $user_id);
            $stmt->execute();

            if ($stmt->rowCount() > 0) {
                $message = '<div class="alert alert-danger">El nombre de usuario ya está en uso por otro usuario.</div>';
            } else {
                $sql = "UPDATE users SET username = :username, role = :role, nombre_asesor = :nombre_asesor";
                $params = [
                    ':username' => $username, 
                    ':role' => $role, 
                    ':nombre_asesor' => $nombre_asesor,
                    ':id' => $user_id
                ];

                if (!empty($password)) {
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $sql .= ", password = :password";
                    $params[':password'] = $hashed_password;
                }

                $sql .= " WHERE id = :id";
                $stmt = $db->prepare($sql);
                
                if ($stmt->execute($params)) {
                     $_SESSION['message'] = '<div class="alert alert-success">Usuario actualizado con éxito.</div>';
                } else {
                     $_SESSION['message'] = '<div class="alert alert-danger">Error al actualizar el usuario.</div>';
                }
                header('Location: manage_users.php');
                exit;
            }
        } catch (PDOException $e) {
            $message = '<div class="alert alert-danger">Error de base de datos: ' . $e->getMessage() . '</div>';
        }
    }
}

// Fetch all users to display in a list
try {
    $db = db();
    $users_stmt = $db->query("SELECT id, username, role, nombre_asesor FROM users ORDER BY username ASC");
    $users = $users_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $users = [];
    $message .= '<div class="alert alert-danger">Error al cargar la lista de usuarios.</div>';
}

$pageTitle = "Gestionar Usuarios";
include 'layout_header.php';
?>

<div class="row">
    <div class="col-md-5">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Crear Nuevo Usuario</h3>
            </div>
            <div class="card-body">
                <?php if(!empty($message)) echo $message; ?>
                <form action="manage_users.php" method="post">
                    <div class="form-group mb-3">
                        <label for="username">Nombre de Usuario</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                    </div>
                    <div class="form-group mb-3">
                        <label for="nombre_asesor">Nombre del Asesor</label>
                        <input type="text" class="form-control" id="nombre_asesor" name="nombre_asesor">
                    </div>
                    <div class="form-group mb-3">
                        <label for="password">Contraseña</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="password" name="password" required>
                            <span class="input-group-text" id="togglePassword" style="cursor: pointer;">👁️</span>
                        </div>
                    </div>
                    <div class="form-group mb-3">
                        <label for="role">Rol</label>
                        <select class="form-control" id="role" name="role" required>
                            <option value="">Seleccione un rol</option>
                            <option value="Administrador">Administrador</option>
                            <option value="Asesor">Asesor</option>
                            <option value="Control Logistico">Control Logístico</option>
                        </select>
                    </div>
                    <button type="submit" name="create_user" class="btn btn-primary w-100">Crear Usuario</button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-md-7">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Usuarios Existentes</h3>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="users-table" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Nombre de Usuario</th>
                                <th>Nombre del Asesor</th>
                                <th>Rol</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($users as $user): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($user['username']); ?></td>
                                    <td><?php echo htmlspecialchars($user['nombre_asesor']); ?></td>
                                    <td><?php echo htmlspecialchars($user['role']); ?></td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editUserModal" 
                                            data-user-id="<?php echo $user['id']; ?>" 
                                            data-username="<?php echo htmlspecialchars($user['username']); ?>" 
                                            data-role="<?php echo htmlspecialchars($user['role']); ?>"
                                            data-nombre-asesor="<?php echo htmlspecialchars($user['nombre_asesor']); ?>">
                                            Editar
                                        </button>
                                        <a href="delete_user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('¿Estás seguro de que quieres eliminar a este usuario?');">Eliminar</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editUserModalLabel">Editar Usuario</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="manage_users.php" method="post">
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="edit-user-id">
                    <div class="form-group mb-3">
                        <label for="edit-username">Nombre de Usuario</label>
                        <input type="text" class="form-control" id="edit-username" name="username" required>
                    </div>
                    <div class="form-group mb-3">
                        <label for="edit-nombre-asesor">Nombre del Asesor</label>
                        <input type="text" class="form-control" id="edit-nombre-asesor" name="nombre_asesor">
                    </div>
                    <div class="form-group mb-3">
                        <label for="edit-password">Nueva Contraseña</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="edit-password" name="password">
                            <span class="input-group-text" id="toggleEditPassword" style="cursor: pointer;">👁️</span>
                        </div>
                        <small class="form-text text-muted">Dejar en blanco para no cambiar la contraseña.</small>
                    </div>
                    <div class="form-group mb-3">
                        <label for="edit-role">Rol</label>
                        <select class="form-control" id="edit-role" name="role" required>
                            <option value="Administrador">Administrador</option>
                            <option value="Asesor">Asesor</option>
                            <option value="Control Logistico">Control Logístico</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                    <button type="submit" name="update_user" class="btn btn-primary">Guardar Cambios</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include 'layout_footer.php'; ?>

<script>
$(document).ready(function() {
    $('#users-table').DataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json"
        }
    });
});

document.addEventListener('DOMContentLoaded', function () {
    const togglePassword = document.querySelector('#togglePassword');
    const password = document.querySelector('#password');

    if (togglePassword) {
        togglePassword.addEventListener('click', function (e) {
            // toggle the type attribute
            const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
            password.setAttribute('type', type);
            // toggle the eye icon
            this.textContent = type === 'password' ? '👁️' : '🙈';
        });
    }

    const toggleEditPassword = document.querySelector('#toggleEditPassword');
    const editPassword = document.querySelector('#edit-password');

    if (toggleEditPassword) {
        toggleEditPassword.addEventListener('click', function (e) {
            // toggle the type attribute
            const type = editPassword.getAttribute('type') === 'password' ? 'text' : 'password';
            editPassword.setAttribute('type', type);
            // toggle the eye icon
            this.textContent = type === 'password' ? '👁️' : '🙈';
        });
    }

    var editUserModal = document.getElementById('editUserModal');
    editUserModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        var userId = button.getAttribute('data-user-id');
        var username = button.getAttribute('data-username');
        var role = button.getAttribute('data-role');
        var nombreAsesor = button.getAttribute('data-nombre-asesor');

        var modal = this;
        modal.querySelector('#edit-user-id').value = userId;
        modal.querySelector('#edit-username').value = username;
        modal.querySelector('#edit-role').value = role;
        modal.querySelector('#edit-nombre-asesor').value = nombreAsesor;
    });
});
</script>
