<?php
/**
 * Módulo Usuarios - Crear
 */

// Configuración inicial
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__)));
}

require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Definir función isLoggedIn si no existe
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

// Definir constantes
define('MIN_PASSWORD_LENGTH', 8);

if (!isLoggedIn()) {
    header('Location: /index.php?module=auth&action=login');
    exit;
}

$db = getDB();
$message = '';
$error = '';

// Obtener roles disponibles
$roles = $db->select("SELECT * FROM roles ORDER BY display_name");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $status = $_POST['status'] ?? 'active';
    $selected_roles = $_POST['roles'] ?? [];
    
    // Validaciones
    if (empty($username) || empty($email) || empty($password) || empty($first_name) || empty($last_name)) {
        $error = 'Todos los campos obligatorios deben ser completados.';
    } elseif ($password !== $confirm_password) {
        $error = 'Las contraseñas no coinciden.';
    } elseif (strlen($password) < MIN_PASSWORD_LENGTH) {
        $error = 'La contraseña debe tener al menos ' . MIN_PASSWORD_LENGTH . ' caracteres.';
    } else {
        // Verificar si el usuario o email ya existen
        $existing = $db->selectOne(
            "SELECT id FROM users WHERE username = ? OR email = ?",
            [$username, $email]
        );
        
        if ($existing) {
            $error = 'El nombre de usuario o email ya están en uso.';
        } else {
            try {
                // Crear usuario
                $ok = $db->execute(
                    "INSERT INTO users (username, email, first_name, last_name, password_hash, status, created_at) 
                     VALUES (?, ?, ?, ?, ?, ?, NOW())",
                    [$username, $email, $first_name, $last_name, password_hash($password, PASSWORD_DEFAULT), $status]
                );
                if (!$ok) {
                    throw new Exception('No se pudo crear el usuario en la base de datos.');
                }
                $user_id = (int)$db->lastInsertId();
                
                // Asignar roles
                if (!empty($selected_roles)) {
                    foreach ($selected_roles as $role_id) {
                        $db->execute(
                            "INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)",
                            [$user_id, (int)$role_id]
                        );
                    }
                }
                
                // Registrar actividad
                $db->execute(
                    "INSERT INTO lead_activities (type, subject, description, created_by, created_at) 
                     VALUES ('system', 'Usuario Creado', ?, ?, NOW())",
                    ["Usuario creado: $username ($email)", $_SESSION['user_id']]
                );
                
                $message = 'Usuario creado exitosamente.';
                
                // Limpiar formulario
                $username = $email = $first_name = $last_name = '';
                $selected_roles = [];
                
            } catch (Exception $e) {
                $error = 'Error al crear el usuario: ' . $e->getMessage();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Crear Usuario - <?php echo APP_NAME; ?></title>
    <link rel="stylesheet" href="/test/simple_crm/public/style.css">
</head>
<body>
    <?php include BASE_PATH . '/modules/shared/header.php'; ?>
    
    <div class="container">
        <div class="card">
            <div class="card-header">
                <h1 class="card-title">Crear Nuevo Usuario</h1>
                <a href="?module=users" class="btn btn-secondary">Volver al Listado</a>
            </div>
            
            <?php if ($error): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <?php if ($message): ?>
                <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <form method="POST" class="form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="username">Nombre de Usuario *</label>
                        <input type="text" id="username" name="username" 
                               value="<?php echo htmlspecialchars($username ?? ''); ?>" 
                               required maxlength="50">
                    </div>
                    
                    <div class="form-group">
                        <label for="email">Email *</label>
                        <input type="email" id="email" name="email" 
                               value="<?php echo htmlspecialchars($email ?? ''); ?>" 
                               required maxlength="100">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="first_name">Nombre *</label>
                        <input type="text" id="first_name" name="first_name" 
                               value="<?php echo htmlspecialchars($first_name ?? ''); ?>" 
                               required maxlength="50">
                    </div>
                    
                    <div class="form-group">
                        <label for="last_name">Apellido *</label>
                        <input type="text" id="last_name" name="last_name" 
                               value="<?php echo htmlspecialchars($last_name ?? ''); ?>" 
                               required maxlength="50">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="password">Contraseña *</label>
                        <input type="password" id="password" name="password" 
                               required minlength="<?php echo MIN_PASSWORD_LENGTH; ?>">
                        <small>Mínimo <?php echo MIN_PASSWORD_LENGTH; ?> caracteres</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password">Confirmar Contraseña *</label>
                        <input type="password" id="confirm_password" name="confirm_password" required>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="status">Estado</label>
                        <select id="status" name="status">
                            <option value="active" <?php echo ($status ?? 'active') === 'active' ? 'selected' : ''; ?>>Activo</option>
                            <option value="inactive" <?php echo ($status ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactivo</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Roles</label>
                        <div class="checkbox-group">
                            <?php foreach ($roles as $role): ?>
                                <label class="checkbox-label">
                                    <input type="checkbox" name="roles[]" value="<?php echo $role['id']; ?>"
                                           <?php echo in_array($role['id'], $selected_roles ?? []) ? 'checked' : ''; ?>>
                                    <?php echo htmlspecialchars($role['display_name']); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-success">Crear Usuario</button>
                    <a href="?module=users" class="btn btn-secondary">Cancelar</a>
                </div>
            </form>
        </div>
    </div>
    
    <script src="/public/script.js"></script>
    <style>
        .checkbox-group {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        .checkbox-label {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: normal;
        }
        .checkbox-label input[type="checkbox"] {
            margin: 0;
        }
    </style>
</body>
</html>