<?php
declare(strict_types=1);
/** BexoGames Portal universal module v1. Bind only to 127.0.0.1. */
const BEXO_PORTAL_EMBEDDED = true;
require_once dirname(__DIR__) . '/src/bootstrap.php';

function bx_json(int $code, array $data): never {
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
function bx_env(string $name): string {return trim((string)(getenv($name) ?: ''));}
function bx_b64(string $value): string {return rtrim(strtr(base64_encode($value), '+/', '-_'), '=');}
function bx_decode(string $value): string|false {
    if (!preg_match('/^[A-Za-z0-9_-]+$/D', $value)) return false;
    return base64_decode(strtr($value, '-_', '+/') . str_repeat('=', (4 - strlen($value) % 4) % 4), true);
}
function bx_secret(string $key): string {
    $s=bx_decode(bx_env($key));
    if ($s===false || strlen($s)<32) bx_json(503,['error'=>'Modulkonfiguration unvollständig']);
    return $s;
}
function bx_config(): array {
    $kid=bx_env('BEXO_BOOKKEEPING_KID');
    $issuer=bx_env('BEXO_BOOKKEEPING_OIDC_ISSUER');
    $origin=bx_env('BEXO_BOOKKEEPING_ORIGIN');
    $id='buchhaltung';
    if(!$kid||!str_starts_with($issuer,'https://')||!str_starts_with($origin,'https://')) bx_json(503,['error'=>'Portalmodul ist noch nicht konfiguriert']);
    return ['kid'=>$kid,'issuer'=>$issuer,'origin'=>$origin,'id'=>$id,'key'=>bx_secret('BEXO_BOOKKEEPING_MODULE_KEY'),'csrf'=>bx_secret('BEXO_BOOKKEEPING_CSRF_KEY')];
}
function bx_assertion(PDO $pdo,array $cfg,bool $permissionsRead=false): array {
    $token=(string)($_SERVER['HTTP_X_BEXO_PORTAL_ASSERTION']??'');
    if(strlen($token)>4096) bx_json(401,['error'=>'Assertion ungültig']);
    $parts=explode('.',$token);
    if(count($parts)!==3) bx_json(401,['error'=>'Assertion fehlt']);
    [$head,$payload,$sig]=$parts;
    $headRaw=bx_decode($head);$claimsRaw=bx_decode($payload);$sigRaw=bx_decode($sig);
    if($headRaw===false||$claimsRaw===false||$sigRaw===false) bx_json(401,['error'=>'Assertion ungültig']);
    $h=json_decode($headRaw,true); $c=json_decode($claimsRaw,true);
    if(!is_array($h)||!is_array($c)||($h['alg']??null)!=='HS256'||($h['typ']??null)!=='JWT'||($h['kid']??null)!==$cfg['kid']) bx_json(401,['error'=>'JWT-Header ungültig']);
    $expected=hash_hmac('sha256',$head.'.'.$payload,$cfg['key'],true);
    if(!hash_equals($expected,$sigRaw)) bx_json(401,['error'=>'Signatur ungültig']);
    $now=time();
    if(($c['iss']??null)!=='bexo-portal'||($c['aud']??null)!==($permissionsRead?'bexo-module:buchhaltung:permissions-read':'bexo-module:buchhaltung')||($c['oidc_issuer']??null)!==$cfg['issuer']||!is_string($c['sub']??null)||($c['sub']??'')===''||strlen($c['sub'])>255||!is_string($c['sid']??null)||strlen($c['sid'])<12||!is_string($c['jti']??null)||!preg_match('/^[A-Za-z0-9_-]{16,128}$/D',$c['jti'])) bx_json(401,['error'=>'JWT-Claims ungültig']);
    if($permissionsRead && (($c['purpose']??null)!=='permissions.read'||($c['target_issuer']??null)!==$cfg['issuer']||!is_string($c['target_sub']??null)||$c['target_sub']===''||strlen($c['target_sub'])>255))bx_json(401,['error'=>'Read-Claims ungültig']);
    foreach(['iat','nbf','exp'] as $field){if(!isset($c[$field])||!is_int($c[$field])) bx_json(401,['error'=>'JWT-Zeit ungültig']);}
    if($c['iat']>$now||$c['iat']<$now-30||$c['nbf']>$now+3||$c['exp']<=$now||$c['exp']-$c['iat']>30||$c['exp']<=$c['iat']) bx_json(401,['error'=>'JWT abgelaufen']);
    try {
        // Atomic uniqueness in shared MySQL storage: protects against replay across PHP workers.
        $pdo->prepare('INSERT INTO portal_assertion_replay(jti,expires_at) VALUES(?,?)')->execute([$c['jti'],$c['exp']+3]);
        if(random_int(1,100)===1)$pdo->prepare('DELETE FROM portal_assertion_replay WHERE expires_at<?')->execute([$now]);
    } catch(Throwable $e){bx_json(401,['error'=>'JWT-Replay oder Sicherheitsdatenbank nicht verfügbar']);}
    return $c;
}
function bx_member(PDO $pdo,array $c): ?array {
    $st=$pdo->prepare('SELECT u.id,u.username,u.display_name,u.role FROM portal_identities p JOIN users u ON u.id=p.user_id WHERE p.oidc_issuer=? AND p.subject=? AND p.active=1 AND u.active=1 AND u.deleted_at IS NULL LIMIT 1');
    $st->execute([$c['oidc_issuer'],$c['sub']]);$u=$st->fetch();return $u?:null;
}
function bx_csrf(array $cfg,array $c): string {
    return bx_b64(hash_hmac('sha256',$c['oidc_issuer']."\0".$c['sub']."\0".$c['sid'],$cfg['csrf'],true));
}
function bx_mutation(array $cfg,array $c): void {
    if(($_SERVER['HTTP_ORIGIN']??'')!==$cfg['origin'] || !hash_equals(bx_csrf($cfg,$c),(string)($_SERVER['HTTP_X_CSRF_TOKEN']??''))) bx_json(403,['error'=>'Origin oder Modul-CSRF ungültig']);
    $portalToken=(string)($_SERVER['HTTP_X_BEXO_PORTAL_CSRF']??'');
    if(strlen($portalToken)<16) bx_json(403,['error'=>'Portal-CSRF fehlt']);
    // Portal BFF alone validates its session CSRF; router validates Origin, presence and module-bound CSRF.
    if (!defined('BEXO_PORTAL_MUTATION_AUTHORIZED')) define('BEXO_PORTAL_MUTATION_AUTHORIZED', true);
}
function bx_broker(PDO $pdo,array $cfg,array $c,string $route): array {
    $secret=bx_secret('BEXO_BOOKKEEPING_BROKER_SECRET');
    $iat=time();
    $h=bx_b64(json_encode(['alg'=>'HS256','typ'=>'JWT']));
    $p=bx_b64(json_encode(['iss'=>'bexo-module:buchhaltung','aud'=>'bexo-portal-broker','sub'=>$c['sub'],'oidc_issuer'=>$c['oidc_issuer'],'module_role'=>'admin','iat'=>$iat,'exp'=>$iat+15,'jti'=>bx_b64(random_bytes(24))]));
    $jwt=$h.'.'.$p.'.'.bx_b64(hash_hmac('sha256',$h.'.'.$p,$secret,true));
    // Only loopback is allowed; no remote URL or arbitrary path can be configured.
    $base=bx_env('BEXO_BOOKKEEPING_BROKER_BASE_URL') ?: 'http://127.0.0.1:4321';
    $parts=parse_url($base);
    if(!is_array($parts)||($parts['scheme']??'')!=='http'||!in_array($parts['host']??'', ['127.0.0.1','localhost','::1'],true)||isset($parts['user'])||isset($parts['pass'])||isset($parts['query'])||isset($parts['fragment'])||!empty($parts['path'])&&$parts['path']!=='/'||!isset($parts['port'])||$parts['port']<1||$parts['port']>65535) bx_json(503,['error'=>'Ungültige interne Broker-Adresse']);
    $url=rtrim($base,'/').'/internal/modules/buchhaltung/users/'.$route;
    $context=stream_context_create(['http'=>['method'=>'GET','timeout'=>5,'ignore_errors'=>true,'header'=>"Authorization: Bearer {$jwt}\r\nAccept: application/json\r\n"]]);
    $raw=@file_get_contents($url,false,$context);
    $status=isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/',$http_response_header[0],$m)?(int)$m[1]:503;
    if($raw===false || $status!==200){
        // No token or secret is exposed; keep the upstream HTTP status for diagnosis.
        $problem=match($status){401=>'Broker-JWT abgewiesen (Schlüssel/Issuer/Claims prüfen)',403=>'Broker-Zugriff verweigert (Moduladmin/Peer prüfen)',404=>'Broker-Endpunkt nicht vorhanden (Portalversion/Port prüfen)',503=>'Broker-Dienst nicht erreichbar oder nicht verfügbar',default=>'Broker-Anfrage fehlgeschlagen'};
        bx_json(503,['error'=>$problem,'brokerStatus'=>$status]);
    }
    $data=json_decode($raw,true);
    if(!is_array($data)) bx_json(503,['error'=>'Broker-Antwort ungültig']);
    return $data;
}

// Never trust forwarded IP headers for the service-peer decision.
if(!in_array($_SERVER['REMOTE_ADDR']??'', ['127.0.0.1','::1'],true)) bx_json(403,['error'=>'Nur privater Dienstzugang']);
$path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH)?:'/';
$method=$_SERVER['REQUEST_METHOD']??'GET';
header('Cache-Control: no-store');header('X-Content-Type-Options: nosniff');
if($path==='/portal/health'&&$method==='GET')bx_json(200,['status'=>'ok']);
$cfg=bx_config();
$readMode=($path==='/portal/permissions/read');
if($readMode && $method!=='POST') bx_json(405,['error'=>'Methode nicht erlaubt']);
$c=bx_assertion($pdo,$cfg,$readMode);
if($readMode){
    $st=$pdo->prepare('SELECT p.active AS linked_active,u.active AS user_active,u.deleted_at,u.role FROM portal_identities p JOIN users u ON u.id=p.user_id WHERE p.oidc_issuer=? AND p.subject=? LIMIT 1');
    $st->execute([$c['target_issuer'],$c['target_sub']]);$target=$st->fetch();
    $access=!$target?'denied':((!$target['linked_active']||!$target['user_active']||$target['deleted_at']!==null)?'inactive':'granted');
    bx_json(200,['schemaVersion'=>1,'moduleId'=>'buchhaltung','target'=>['issuer'=>$c['target_issuer'],'sub'=>$c['target_sub']],'access'=>$access,'roles'=>$access==='granted'?[$target['role']]:[],'details'=>[]]);
}
if($path==='/portal/manifest'&&$method==='GET') bx_json(200,['schemaVersion'=>1,'id'=>'buchhaltung','name'=>'Buchhaltung','description'=>'BexoGames Finanzverwaltung','version'=>'1.1.1','icon'=>'wallet']);
$member=bx_member($pdo,$c);
if($path==='/portal/access'&&$method==='POST') bx_json(200,['schemaVersion'=>1,'moduleId'=>'buchhaltung','allowed'=>(bool)$member,'roles'=>$member?[($member['role']==='admin'?'admin':($member['role']==='viewer'?'viewer':'member'))]:[]]);
if(!$member) bx_json(403,['error'=>'Keine Buchhaltungsberechtigung']);
// Each request rechecks local membership, no automatic accounts or role assignment.
$identityKey=hash('sha256',$c['oidc_issuer']."\0".$c['sub']."\0".$c['sid']);
if(($_SESSION['bexo_portal_identity']??'')!==$identityKey){
    // No standalone authenticated state is reused on a Portal identity change.
    $_SESSION=[];$_SESSION['bexo_portal_identity']=$identityKey;
}
$_SESSION['user']=['id'=>(int)$member['id'],'username'=>$member['username'],'display_name'=>$member['display_name'],'role'=>$member['role']];
$_SESSION['bexo_portal_identity']=$identityKey;
if($path==='/portal/navigation'&&$method==='GET'){
    $items=[['id'=>'overview','label'=>'Übersicht','icon'=>'layout-dashboard','path'=>'/'],['id'=>'bookings','label'=>'Buchungen','icon'=>'file-text','path'=>'/bookings'],['id'=>'templates','label'=>'Vorlagen','icon'=>'calendar-days','path'=>'/templates'],['id'=>'reports','label'=>'Auswertungen','icon'=>'chart-no-axes-column','path'=>'/reports']];
    if($member['role']==='admin'){
        $items[]=['id'=>'accounts','label'=>'Konten','icon'=>'wallet','path'=>'/accounts'];
        $items[]=['id'=>'audit','label'=>'Protokoll','icon'=>'history','path'=>'/audit'];
        $items[]=['id'=>'users','label'=>'Benutzer','icon'=>'users','path'=>'/users'];
        
    }
    bx_json(200,['schemaVersion'=>1,'items'=>$items]);
}
if($path==='/api/bootstrap'&&$method==='GET')bx_json(200,['csrfToken'=>bx_csrf($cfg,$c),'user'=>['displayName'=>$member['display_name'],'role'=>$member['role']]]);
if(str_starts_with($path,'/api/portal-users/')){
    if($member['role']!=='admin')bx_json(403,['error'=>'Nur Administratoren']);
    if($path==='/api/portal-users/search'&&$method==='GET'){
        $q=trim((string)($_GET['search']??''));if(strlen($q)<2||strlen($q)>80)bx_json(400,['error'=>'Suche: 2–80 Zeichen']);
        $result=bx_broker($pdo,$cfg,$c,'search?search='.rawurlencode($q).'&limit=20');
        foreach(($result['users']??[]) as &$item){
            if(!is_array($item)||!is_string($item['subject']??null)||strlen($item['subject'])>255)continue;
            $st=$pdo->prepare('SELECT p.user_id,p.active,u.role,u.display_name FROM portal_identities p JOIN users u ON u.id=p.user_id WHERE p.oidc_issuer=? AND p.subject=? LIMIT 1');
            $st->execute([$cfg['issuer'],$item['subject']]);$found=$st->fetch();
            if($found)$item['membership']=['active'=>(bool)$found['active'],'role'=>$found['role'],'displayName'=>$found['display_name']];
        }unset($item);
        bx_json(200,$result);
    }
    if($path==='/api/portal-users/resolve'&&$method==='GET'){
        $sub=(string)($_GET['subject']??'');if(!$sub||strlen($sub)>255)bx_json(400,['error'=>'Subject ungültig']);
        bx_json(200,bx_broker($pdo,$cfg,$c,'resolve?subject='.rawurlencode($sub)));
    }
    if($path==='/api/portal-users/link'&&$method==='POST'){
        bx_mutation($cfg,$c);
        $input=json_decode(file_get_contents('php://input'),true);
        if(!is_array($input))bx_json(400,['error'=>'Eingabe ungültig']);
        $subject=(string)($input['subject']??'');$userId=(int)($input['userId']??0);
        if(!$subject||strlen($subject)>255||$userId<=0||($input['confirmed']??false)!==true)bx_json(400,['error'=>'Explizite Bestätigung erforderlich']);
        $resolved=bx_broker($pdo,$cfg,$c,'resolve?subject='.rawurlencode($subject));
        $u=$resolved['user']??null;
        if(!is_array($u)||($u['subject']??null)!==$subject||($u['issuer']??null)!==$cfg['issuer']||($u['active']??null)!==true)bx_json(403,['error'=>'Identität vom Broker nicht bestätigt']);
        $st=$pdo->prepare('SELECT id FROM users WHERE id=? AND active=1 AND deleted_at IS NULL');$st->execute([$userId]);if(!$st->fetch())bx_json(404,['error'=>'Lokaler Benutzer nicht aktiv']);
        $old=$pdo->prepare('SELECT user_id,active FROM portal_identities WHERE oidc_issuer=? AND subject=?');$old->execute([$cfg['issuer'],$subject]);$before=$old->fetch()?:null;
        if($before && (int)$before['user_id']!==$userId)bx_json(409,['error'=>'Identität bereits einem anderen Konto zugeordnet']);
        $st=$pdo->prepare('SELECT subject FROM portal_identities WHERE oidc_issuer=? AND user_id=? AND subject<>? LIMIT 1');
        $st->execute([$cfg['issuer'],$userId,$subject]);
        if($st->fetchColumn())bx_json(409,['error'=>'Lokales Konto ist bereits mit einem anderen Authentik-Konto verknüpft']);
        $pdo->prepare('INSERT INTO portal_identities(oidc_issuer,subject,user_id,active) VALUES(?,?,?,1) ON DUPLICATE KEY UPDATE active=1')->execute([$cfg['issuer'],$subject,$userId]);
        audit($pdo,'portal.identity.link','user',$userId,$before,['issuer'=>$cfg['issuer'],'subject'=>$subject]);
        bx_json(200,['linked'=>true]);
    }
    if($path==='/api/portal-users/restore'&&$method==='POST'){
        bx_mutation($cfg,$c);$input=json_decode(file_get_contents('php://input'),true);
        $subject=is_array($input)?(string)($input['subject']??''):'';
        $role=is_array($input)?(string)($input['role']??''):'';
        if(!$subject||strlen($subject)>255||!in_array($role,['admin','bookkeeper','viewer'],true)||($input['confirmed']??false)!==true)bx_json(400,['error'=>'Ungültige Eingaben']);
        $resolved=bx_broker($pdo,$cfg,$c,'resolve?subject='.rawurlencode($subject));$u=$resolved['user']??null;
        if(!is_array($u)||($u['subject']??null)!==$subject||($u['issuer']??null)!==$cfg['issuer']||($u['active']??null)!==true)bx_json(403,['error'=>'Authentik-Benutzer nicht bestätigt']);
        $pdo->beginTransaction();
        try {
            $st=$pdo->prepare('SELECT p.user_id,p.active,u.deleted_at FROM portal_identities p JOIN users u ON u.id=p.user_id WHERE p.oidc_issuer=? AND p.subject=? FOR UPDATE');
            $st->execute([$cfg['issuer'],$subject]);$before=$st->fetch();
            if(!$before)throw new DomainException('Keine frühere Buchhaltungszuordnung vorhanden');
            if((int)$before['active']===1)throw new DomainException('Benutzer ist bereits aufgenommen');
            $id=(int)$before['user_id'];
            // The historic internal user id is intentionally preserved.
            $pdo->prepare('UPDATE users SET active=1,deleted_at=NULL,role=? WHERE id=?')->execute([$role,$id]);
            $pdo->prepare('UPDATE portal_identities SET active=1 WHERE oidc_issuer=? AND subject=?')->execute([$cfg['issuer'],$subject]);
            audit($pdo,'portal.member.restore','user',$id,['active'=>false],['active'=>true,'role'=>$role,'subject'=>$subject]);
            $pdo->commit();bx_json(200,['restored'=>true]);
        }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();bx_json($e instanceof DomainException?409:500,['error'=>$e instanceof DomainException?$e->getMessage():'Wiederaufnahme fehlgeschlagen']);}
    }
    if($path==='/api/portal-users/create'&&$method==='POST'){
        bx_mutation($cfg,$c);
        $input=json_decode(file_get_contents('php://input'),true);
        if(!is_array($input)||($input['confirmed']??false)!==true)bx_json(400,['error'=>'Bestätigung erforderlich']);
        $subject=(string)($input['subject']??'');$role=(string)($input['role']??'viewer');
        if($subject===''||strlen($subject)>255||!in_array($role,['admin','bookkeeper','viewer'],true))bx_json(400,['error'=>'Ungültige Eingaben']);
        $resolved=bx_broker($pdo,$cfg,$c,'resolve?subject='.rawurlencode($subject));$u=$resolved['user']??null;
        if(!is_array($u)||($u['subject']??null)!==$subject||($u['issuer']??null)!==$cfg['issuer']||($u['active']??null)!==true)bx_json(403,['error'=>'Identität nicht bestätigt']);
        $username=trim((string)($u['username']??''));$display=trim((string)($u['name']??''));
        if($username===''||strlen($username)>80||$display===''||strlen($display)>120)bx_json(422,['error'=>'Broker-Benutzerdaten ungültig']);
        try{
            $pdo->beginTransaction();
            $st=$pdo->prepare('SELECT id FROM portal_identities WHERE oidc_issuer=? AND subject=?');$st->execute([$cfg['issuer'],$subject]);
            if($st->fetchColumn())throw new DomainException('Authentik-Benutzer bereits zugeordnet');
            $st=$pdo->prepare('SELECT id FROM users WHERE username=?');$st->execute([$username]);
            if($st->fetchColumn())throw new DomainException('Benutzername existiert bereits: bitte vorhandenes Konto verknüpfen');
            $pdo->prepare('INSERT INTO users(username,display_name,password_hash,role,active) VALUES(?,?,NULL,?,1)')->execute([$username,$display,$role]);
            $userId=(int)$pdo->lastInsertId();
            $pdo->prepare('INSERT INTO portal_identities(oidc_issuer,subject,user_id,active) VALUES(?,?,?,1)')->execute([$cfg['issuer'],$subject,$userId]);
            audit($pdo,'create','user',$userId,null,['username'=>$username,'role'=>$role,'source'=>'authentik']);
            audit($pdo,'portal.identity.link','user',$userId,null,['issuer'=>$cfg['issuer'],'subject'=>$subject]);
            $pdo->commit();bx_json(200,['created'=>true]);
        }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();bx_json($e instanceof DomainException?409:500,['error'=>$e instanceof DomainException?$e->getMessage():'Benutzer konnte nicht angelegt werden']);}
    }
    if($path==='/api/portal-users/remove'&&$method==='POST'){
        bx_mutation($cfg,$c);$input=json_decode(file_get_contents('php://input'),true);
        $subject=is_array($input)?(string)($input['subject']??''):'';
        if(!$subject||strlen($subject)>255||($input['confirmed']??false)!==true)bx_json(400,['error'=>'Bestätigung erforderlich']);
        $st=$pdo->prepare('SELECT p.user_id,u.role,u.active,u.deleted_at FROM portal_identities p JOIN users u ON u.id=p.user_id WHERE p.oidc_issuer=? AND p.subject=?');$st->execute([$cfg['issuer'],$subject]);$target=$st->fetch();
        if(!$target)bx_json(404,['error'=>'Verknüpfung nicht gefunden']);
        if($subject===$c['sub'])bx_json(409,['error'=>'Eigenen Portalzugang nicht entfernen']);
        $pdo->beginTransaction();
        try{
            if($target['role']==='admin'&&$target['active']&&$target['deleted_at']===null){
                $count=(int)$pdo->query("SELECT COUNT(*) FROM portal_identities p JOIN users u ON u.id=p.user_id WHERE p.active=1 AND u.active=1 AND u.deleted_at IS NULL AND u.role='admin'")->fetchColumn();
                if($count<=1)throw new DomainException('Letzten Portaladministrator nicht entfernen');
            }
            $pdo->prepare('UPDATE portal_identities SET active=0 WHERE oidc_issuer=? AND subject=?')->execute([$cfg['issuer'],$subject]);
            audit($pdo,'portal.member.remove','user',(int)$target['user_id'],['active'=>true],['active'=>false,'subject'=>$subject]);
            $pdo->commit();bx_json(200,['disabled'=>true]);
        }catch(Throwable $e){$pdo->rollBack();bx_json($e instanceof DomainException?409:500,['error'=>$e instanceof DomainException?$e->getMessage():'Benutzer konnte nicht entfernt werden']);}
    }
    bx_json(404,['error'=>'API nicht gefunden']);
}
if($method==='POST')bx_mutation($cfg,$c);
if($path==='/api/form'&&$method==='POST'){
    $page=(string)($_GET['page']??'');
    if(!in_array($page,['bookings','templates','accounts','users'],true))bx_json(404,['error'=>'Formular nicht gefunden']);
    header('Content-Type: application/json; charset=utf-8');
    header('X-Frame-Options: DENY');
    require dirname(__DIR__).'/public/index.php';exit;
}
// On the authenticated private backend, assets are served explicitly, never via built-in static fallback.
if(preg_match('~^/assets/(app\.(?:css|js))$~D',$path,$m)&&$method==='GET'){
    header('Content-Type: '.(str_ends_with($path,'.css')?'text/css':'application/javascript').'; charset=utf-8');
    header('Cache-Control: private, no-cache');
    readfile(dirname(__DIR__).'/public/assets/'.$m[1]);exit;
}
if($path==='/portal-ui.js'&&$method==='GET'){
    header('Content-Type: application/javascript; charset=utf-8');readfile(__DIR__.'/portal-ui.js');exit;
}
$routes=['/'=>'dashboard','/bookings'=>'bookings','/templates'=>'templates','/accounts'=>'accounts','/reports'=>'reports','/audit'=>'audit','/users'=>'users','/portal-members'=>'portal-members'];
if($method==='GET'||$method==='POST'){
    if(!isset($routes[$path]))bx_json(404,['error'=>'Seite nicht gefunden']);
    if(!isset($_GET['page']))$_GET['page']=$routes[$path];
    header('X-Frame-Options: SAMEORIGIN');
    header("Content-Security-Policy: frame-ancestors 'self'");
    require dirname(__DIR__).'/public/index.php';exit;
}
bx_json(405,['error'=>'Methode nicht erlaubt']);
