<?php
$pageTitle = 'Nuevo Usuario';
require_once __DIR__ . '/../../config/config.php';
requireLogin();

if ($_SESSION['rol'] != 'admin') {
    header('Location: ' . SITE_URL);
    exit;
}

$db = getDB();
$modulos = getModulosDisponibles();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitize($_POST['email']);
    
    // Verificar email único
    $stmt = $db->prepare("SELECT id FROM usuarios WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        showAlert('El email ya está registrado', 'danger');
    } else {
        try {
            $db->beginTransaction();
            
            // Procesar firma si es laboratorista
            $firma = null;
            $firma_ext = null;
            if ($_POST['rol'] == 'laboratorista' && isset($_FILES['firma']) && $_FILES['firma']['error'] == 0) {
                $allowed = ['png'];
                $ext = strtolower(pathinfo($_FILES['firma']['name'], PATHINFO_EXTENSION));
                if (in_array($ext, $allowed) && $_FILES['firma']['size'] <= 1048576) {
                    $firma = file_get_contents($_FILES['firma']['tmp_name']);
                    $firma_ext = $ext;
                }
            }
            
            $stmt = $db->prepare("
                INSERT INTO usuarios (nombre, email, password, rol, activo, firma, firma_extension)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                sanitize($_POST['nombre']),
                $email,
                password_hash($_POST['password'], PASSWORD_DEFAULT),
                sanitize($_POST['rol']),
                isset($_POST['activo']) ? 1 : 0,
                $firma,
                $firma_ext
            ]);
            
            $usuario_id = $db->lastInsertId();
            
            // Guardar permisos personalizados o por defecto
            if (isset($_POST['permisos_personalizados']) && $_POST['permisos_personalizados'] == '1') {
                $permisos = [];
                foreach ($modulos as $modulo => $info) {
                    if (isset($_POST['permiso'][$modulo])) {
                        $permisos[$modulo] = [
                            'ver' => isset($_POST['permiso'][$modulo]['ver']) ? 1 : 0,
                            'crear' => isset($_POST['permiso'][$modulo]['crear']) ? 1 : 0,
                            'editar' => isset($_POST['permiso'][$modulo]['editar']) ? 1 : 0,
                            'eliminar' => isset($_POST['permiso'][$modulo]['eliminar']) ? 1 : 0
                        ];
                    }
                }
                guardarPermisosUsuario($usuario_id, $permisos);
            } else {
                asignarPermisosDefecto($usuario_id, $_POST['rol']);
            }
            
            $db->commit();
            showAlert('Usuario creado correctamente');
            header('Location: list.php');
            exit;
        } catch (PDOException $e) {
            $db->rollBack();
            showAlert('Error al crear: ' . $e->getMessage(), 'danger');
        }
    }
}

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

<div class="d-flex justify-content-between align-items-center mt-4 mb-4">
    <h2><i class="bi bi-person-plus"></i> Nuevo Usuario</h2>
    <a href="list.php" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left"></i> Volver
    </a>
</div>

<div class="row justify-content-center">
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label class="form-label">Nombre Completo *</label>
                        <input type="text" name="nombre" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Correo Electrónico *</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Contraseña *</label>
                        <input type="password" name="password" class="form-control" required minlength="6">
                        <small class="text-muted">Mínimo 6 caracteres</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Rol *</label>
                        <select name="rol" class="form-select" id="rol" required>
                            <option value="recepcion">Recepción</option>
                            <option value="laboratorista">Laboratorista</option>
                            <option value="caja">Caja</option>
                            <option value="admin">Administrador</option>
                        </select>
                    </div>
                    
                    <div class="mb-3" id="firmaSection" style="display: none;">
                        <label class="form-label">Firma Digital (PNG)</label>
                        <input type="file" name="firma" class="form-control" accept="image/png">
                        <small class="text-muted">Solo PNG. Máximo 1MB. Fondo transparente recomendado.</small>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="activo" id="activo" checked>
                        <label class="form-check-label" for="activo">Usuario Activo</label>
                    </div>
                    
                    <!-- Sección de Permisos -->
                    <div class="card mb-3">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-shield-lock"></i> Permisos de Módulos</span>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="permisos_personalizados" 
                                       id="permisosPersonalizados" value="1">
                                <label class="form-check-label" for="permisosPersonalizados">
                                    <small>Personalizar</small>
                                </label>
                            </div>
                        </div>
                        <div class="card-body" id="permisosContainer" style="display: none;">
                            <small class="text-muted d-block mb-3">
                                <i class="bi bi-info-circle"></i> Si no personaliza, se asignarán permisos por defecto según el rol.
                            </small>
                            <div class="table-responsive">
                                <table class="table table-sm table-bordered">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Módulo</th>
                                            <th class="text-center" style="width: 70px;">Ver</th>
                                            <th class="text-center" style="width: 70px;">Crear</th>
                                            <th class="text-center" style="width: 70px;">Editar</th>
                                            <th class="text-center" style="width: 70px;">Eliminar</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($modulos as $modulo => $info): 
                                            if (isset($info['admin_only']) && $info['admin_only']) continue;
                                        ?>
                                        <tr>
                                            <td>
                                                <i class="bi <?= $info['icono'] ?>"></i> <?= $info['nombre'] ?>
                                            </td>
                                            <td class="text-center">
                                                <input type="checkbox" class="form-check-input" 
                                                       name="permiso[<?= $modulo ?>][ver]" value="1">
                                            </td>
                                            <td class="text-center">
                                                <input type="checkbox" class="form-check-input" 
                                                       name="permiso[<?= $modulo ?>][crear]" value="1">
                                            </td>
                                            <td class="text-center">
                                                <input type="checkbox" class="form-check-input" 
                                                       name="permiso[<?= $modulo ?>][editar]" value="1">
                                            </td>
                                            <td class="text-center">
                                                <input type="checkbox" class="form-check-input" 
                                                       name="permiso[<?= $modulo ?>][eliminar]" value="1">
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <div class="btn-group btn-group-sm">
                                <button type="button" class="btn btn-outline-primary" onclick="marcarTodos(true)">
                                    Marcar Todos
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="marcarTodos(false)">
                                    Desmarcar Todos
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-lg"></i> Crear Usuario
                        </button>
                        <a href="list.php" class="btn btn-outline-secondary">Cancelar</a>
                    </div>
                </form>
                
                <script>
                document.getElementById('rol').addEventListener('change', function() {
                    document.getElementById('firmaSection').style.display = 
                        this.value === 'laboratorista' ? 'block' : 'none';
                });
                
                document.getElementById('permisosPersonalizados').addEventListener('change', function() {
                    document.getElementById('permisosContainer').style.display = 
                        this.checked ? 'block' : 'none';
                });
                
                function marcarTodos(estado) {
                    document.querySelectorAll('#permisosContainer input[type="checkbox"]').forEach(cb => {
                        cb.checked = estado;
                    });
                }
                </script>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
