<?php
require_once __DIR__ . '/../../vendor/autoload.php';

use App\Controllers\UserController;
use App\Middleware\RoleMiddleware;

// Middleware maneja la seguridad
$controller = new UserController();
$users = $controller->index(); // Maneja POST internamente y retorna lista para render

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestión de Usuarios - Contenedor Ibiza</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        .modal {
            display: none;
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.5);
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        .modal-content {
            background: white;
            padding: 2rem;
            border-radius: 1rem;
            width: 100%;
            max-width: 500px;
        }
    </style>
</head>
<body>
    <?php include '../partials/navbar.php'; ?>

    <div class="container">
        <div class="card-header">
            <h1 class="card-title">👥 Gestión de Usuarios</h1>
            <button onclick="openModal('createModal')" class="btn btn-primary">Nuevo Usuario</button>
        </div>

        <?php if ($msg = flash('success')): ?>
            <div class="alert alert-success"><?= e($msg) ?></div>
        <?php endif; ?>
        
        <?php if ($msg = flash('error')): ?>
            <div class="alert alert-error"><?= e($msg) ?></div>
        <?php endif; ?>

        <div class="card">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Usuario</th>
                            <th>Nombre Completo</th>
                            <th>Rol</th>
                            <th>Estado</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $u): ?>
                            <tr>
                                <td><?= e($u['username']) ?></td>
                                <td><?= e($u['full_name']) ?></td>
                                <td>
                                    <?php
                                    $roles = [
                                        'admin' => 'Administrador',
                                        'coordinador' => 'Coordinador',
                                        'ayudante' => 'Ayudante'
                                    ];
                                    echo $roles[$u['role']] ?? $u['role'];
                                    ?>
                                </td>
                                <td>
                                    <?php if ($u['active']): ?>
                                        <span class="badge badge-success">Activo</span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">Inactivo</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="flex">
                                        <?php 
                                        $canManage = $_SESSION['role'] === 'admin' || ($_SESSION['role'] === 'coordinador' && $u['role'] !== 'admin');
                                        ?>
                                        
                                        <?php if ($canManage): ?>
                                            <button onclick='editUser(<?= json_encode($u) ?>)' class="btn btn-sm btn-secondary">Editar</button>
                                            
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                                                <input type="hidden" name="action" value="toggle">
                                                <input type="hidden" name="id" value="<?= $u['id'] ?>">
                                                <?php if ($u['active']): ?>
                                                    <button type="submit" class="btn btn-sm btn-danger">Desactivar</button>
                                                <?php else: ?>
                                                    <button type="submit" class="btn btn-sm btn-success">Activar</button>
                                                <?php endif; ?>
                                            </form>
                                        <?php else: ?>
                                            <span class="badge badge-secondary">Solo lectura</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal Crear -->
    <div id="createModal" class="modal">
        <div class="modal-content">
            <h2 class="mb-4">Nuevo Usuario</h2>
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                <input type="hidden" name="action" value="create">
                
                <div class="form-group">
                    <label class="form-label">Nombre de Usuario</label>
                    <input type="text" name="username" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Contraseña</label>
                    <input type="password" name="password" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Nombre Completo</label>
                    <input type="text" name="full_name" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Rol</label>
                    <select name="role" class="form-control">
                        <option value="ayudante">Ayudante</option>
                        <option value="coordinador">Coordinador</option>
                        <?php if ($_SESSION['role'] === 'admin'): ?>
                            <option value="admin">Administrador</option>
                        <?php endif; ?>
                    </select>
                </div>
                
                <div class="flex justify-end mt-4">
                    <button type="button" onclick="closeModal('createModal')" class="btn btn-secondary">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Crear</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal Editar -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <h2 class="mb-4">Editar Usuario</h2>
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" id="edit_id">
                
                <div class="form-group">
                    <label class="form-label">Nombre de Usuario</label>
                    <input type="text" name="username" id="edit_username" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Nueva Contraseña (Dejar en blanco para no cambiar)</label>
                    <input type="password" name="password" class="form-control">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Nombre Completo</label>
                    <input type="text" name="full_name" id="edit_fullname" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Rol</label>
                    <select name="role" id="edit_role" class="form-control">
                        <option value="ayudante">Ayudante</option>
                        <option value="coordinador">Coordinador</option>
                        <?php if ($_SESSION['role'] === 'admin'): ?>
                            <option value="admin">Administrador</option>
                        <?php endif; ?>
                    </select>
                </div>
                
                <div class="flex justify-end mt-4">
                    <button type="button" onclick="closeModal('editModal')" class="btn btn-secondary">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Guardar</button>
                </div>
            </form>
        </div>
    </div>

    <script src="../assets/js/main.js"></script>
    <script>
        function editUser(user) {
            document.getElementById('edit_id').value = user.id;
            document.getElementById('edit_username').value = user.username;
            document.getElementById('edit_fullname').value = user.full_name;
            document.getElementById('edit_role').value = user.role;
            openModal('editModal');
        }
    </script>
</body>
</html>
