<?php
NexoraRbac::requirePermission('system.manage');

if(!NexoraRealm::platformEnabled()) {
    echo '<div class="alert alert-warning"><strong>Platform no está activado.</strong> Ejecuta la migración de staging y habilita <code>NEXORA_PLATFORM_ENABLED</code> para administrar roles desde aquí.</div>';
    return;
}

$db = Connection::Database('Platform');
$message = null;
$error = null;

try {
    if($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = isset($_POST['nexora_action']) ? $_POST['nexora_action'] : '';
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $role = isset($_POST['role_key']) ? trim($_POST['role_key']) : '';

        if(!Validator::UsernameLength($username) || !Validator::AlphaNumeric($username)) {
            throw new RuntimeException('El usuario no cumple el formato de cuenta del servidor.');
        }
        $roleRow = $db->query_fetch_single('SELECT role_key FROM NEXORA_ROLES WHERE role_key = ?', array($role));
        if(!is_array($roleRow)) throw new RuntimeException('El rol seleccionado no existe.');

        if($action === 'assign') {
            $exists = false;
            foreach(NexoraRealm::ids() as $realmId) {
                $realmDb = Connection::Database('Me_MuOnline', $realmId);
                $row = $realmDb->query_fetch_single('SELECT TOP 1 '._CLMN_USERNM_.' FROM '._TBL_MI_.' WHERE '._CLMN_USERNM_.' = ?', array($username));
                if(is_array($row)) { $exists = true; break; }
            }
            if(!$exists) throw new RuntimeException('La cuenta no existe en los realms configurados.');
            $already = $db->query_fetch_single('SELECT username FROM NEXORA_USER_ROLES WHERE username = ? AND role_key = ?', array($username, $role));
            if(!is_array($already)) {
                $db->query('INSERT INTO NEXORA_USER_ROLES (username, role_key, created_by) VALUES (?, ?, ?)', array($username, $role, $_SESSION['username']));
            }
            NexoraRbac::clearRuntimeCache();
            NexoraAudit::log('rbac.role_assigned', 'account', $username, null, array('role'=>$role));
            $message = 'Rol asignado.';
        } elseif($action === 'remove') {
            if($username === $_SESSION['username'] && $role === 'superadmin') throw new RuntimeException('No puedes retirar tu propio superadmin desde esta pantalla.');
            $db->query('DELETE FROM NEXORA_USER_ROLES WHERE username = ? AND role_key = ?', array($username, $role));
            NexoraRbac::clearRuntimeCache();
            NexoraAudit::log('rbac.role_removed', 'account', $username, array('role'=>$role), null);
            $message = 'Rol retirado.';
        }
    }
} catch(Throwable $e) {
    $error = $e->getMessage();
}

$roles = $db->query_fetch('SELECT role_key, role_label FROM NEXORA_ROLES ORDER BY role_label');
$assignments = $db->query_fetch('SELECT ur.username, ur.role_key, r.role_label, ur.created_by, ur.created_at FROM NEXORA_USER_ROLES ur LEFT JOIN NEXORA_ROLES r ON r.role_key = ur.role_key ORDER BY ur.username, ur.role_key');
?>
<div class="row">
    <div class="col-lg-12"><h1 class="page-header">Access Control</h1></div>
</div>
<?php if($message) echo '<div class="alert alert-success">'.htmlspecialchars($message, ENT_QUOTES, 'UTF-8').'</div>'; ?>
<?php if($error) echo '<div class="alert alert-danger">'.htmlspecialchars($error, ENT_QUOTES, 'UTF-8').'</div>'; ?>
<div class="row">
    <div class="col-md-5">
        <div class="panel panel-default">
            <div class="panel-heading"><strong>Asignar responsabilidad</strong></div>
            <div class="panel-body">
                <p class="text-muted">Los administradores heredados de <code>webengine.json</code> conservan superadmin por compatibilidad. Este panel agrega roles granulares sin tocar esa lista.</p>
                <form method="post">
                    <input type="hidden" name="nexora_action" value="assign">
                    <div class="form-group"><label>Cuenta</label><input class="form-control" name="username" maxlength="10" required></div>
                    <div class="form-group"><label>Rol</label><select class="form-control" name="role_key" required>
                        <?php if(is_array($roles)) foreach($roles as $row) echo '<option value="'.htmlspecialchars($row['role_key'], ENT_QUOTES, 'UTF-8').'">'.htmlspecialchars($row['role_label'], ENT_QUOTES, 'UTF-8').'</option>'; ?>
                    </select></div>
                    <button class="btn btn-primary" type="submit">Asignar rol</button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-md-7">
        <div class="panel panel-default">
            <div class="panel-heading"><strong>Asignaciones activas</strong></div>
            <div class="panel-body table-responsive">
                <table class="table table-striped table-condensed">
                    <thead><tr><th>Cuenta</th><th>Rol</th><th>Asignado por</th><th></th></tr></thead>
                    <tbody>
                    <?php if(is_array($assignments) && count($assignments)) { foreach($assignments as $row) { ?>
                        <tr>
                            <td><?php echo htmlspecialchars($row['username'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars($row['role_label'] ?: $row['role_key'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars((string)$row['created_by'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td class="text-right"><form method="post" style="display:inline"><input type="hidden" name="nexora_action" value="remove"><input type="hidden" name="username" value="<?php echo htmlspecialchars($row['username'], ENT_QUOTES, 'UTF-8'); ?>"><input type="hidden" name="role_key" value="<?php echo htmlspecialchars($row['role_key'], ENT_QUOTES, 'UTF-8'); ?>"><button class="btn btn-xs btn-danger" type="submit">Retirar</button></form></td>
                        </tr>
                    <?php }} else { ?><tr><td colspan="4" class="text-muted">Sin asignaciones en Platform. Los admins heredados siguen funcionando.</td></tr><?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
