<?php

// Direct PDO connection to check role permissions
$config = include 'data/config-internal.php';
$db = $config['database'];

try {
    $pdo = new PDO(
        "mysql:host={$db['host']};dbname={$db['dbname']}",
        $db['user'],
        $db['password']
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $targetRole = 'api-user-motia';

    echo "=== Rolle: $targetRole ===\n\n";

    // 1. Rolle in DB finden
    $stmt = $pdo->prepare("SELECT id, name, data FROM role WHERE name = ?");
    $stmt->execute([$targetRole]);
    $role = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$role) {
        echo "FEHLER: Rolle '$targetRole' nicht gefunden!\n";

        // Alle Rollen auflisten
        echo "\nVorhandene Rollen:\n";
        $stmt = $pdo->query("SELECT id, name FROM role ORDER BY name");
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
            echo "  - {$r['name']} (id: {$r['id']})\n";
        }
        exit(1);
    }

    echo "Rollen-ID: {$role['id']}\n\n";

    $data = json_decode($role['data'], true);
    if (!$data) {
        echo "FEHLER: Rollen-Daten konnten nicht geparst werden.\n";
        echo "Raw data: " . substr($role['data'], 0, 500) . "\n";
        exit(1);
    }

    // 2. Scope-Permissions anzeigen (table-Abschnitt)
    $table = $data['table'] ?? [];

    echo "=== Scope-Permissions (table) ===\n";
    $interesting = ['CAkten', 'CAdvowareAkten', 'CAktenCDokumente', 'CAdvowareAktenCDokumente', 'CDokumente', 'CAIKnowledge', 'CAICollection'];
    echo "\nGezielte Suche nach relevanten Entitäten:\n";
    echo str_repeat("-", 60) . "\n";
    printf("%-40s %-10s %-10s\n", "Entität", "create", "read");
    echo str_repeat("-", 60) . "\n";

    foreach ($interesting as $entity) {
        if (isset($table[$entity])) {
            $perms = $table[$entity];
            $create = $perms['create'] ?? '(n/a)';
            $read   = $perms['read']   ?? '(n/a)';
            printf("%-40s %-10s %-10s\n", $entity, $create, $read);
        } else {
            printf("%-40s %-10s\n", $entity, '--- FEHLT ---');
        }
    }

    echo "\n=== Alle Scope-Einträge (table) ===\n";
    echo str_repeat("-", 60) . "\n";
    ksort($table);
    foreach ($table as $entity => $perms) {
        $read   = $perms['read']   ?? '-';
        $create = $perms['create'] ?? '-';
        $edit   = $perms['edit']   ?? '-';
        $delete = $perms['delete'] ?? '-';
        printf("%-40s read=%-8s create=%-8s edit=%-8s delete=%-8s\n", $entity, $read, $create, $edit, $delete);
    }

    // 3. Field-Permissions anzeigen
    $fieldTable = $data['fieldTable'] ?? [];
    echo "\n=== Feld-Permissions (fieldTable) für relevante Entitäten ===\n";
    foreach ($interesting as $entity) {
        if (isset($fieldTable[$entity])) {
            echo "\n  $entity:\n";
            foreach ($fieldTable[$entity] as $field => $perm) {
                echo "    $field: " . json_encode($perm) . "\n";
            }
        }
    }

    // 4. API-User → Rolle Zuordnung prüfen
    echo "\n=== API-User mit Rolle '$targetRole' ===\n";
    $stmt = $pdo->query("
        SELECT u.id, u.user_name, u.name, u.type, u.is_active
        FROM `user` u
        JOIN entity_user eu ON eu.user_id = u.id
        JOIN role r ON r.id = eu.entity_id AND eu.entity_type = 'Role'
        WHERE r.name = " . $pdo->quote($targetRole)
    );
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if ($users) {
        foreach ($users as $u) {
            $active = $u['is_active'] ? 'aktiv' : 'inaktiv';
            echo "  - {$u['user_name']} ({$u['name']}) type={$u['type']} [$active]\n";
        }
    } else {
        echo "  Keine User direkt zugeordnet.\n";
        // Alternativ: per teams oder direkte Rollen-ID im User
        $stmt2 = $pdo->prepare("SELECT id, user_name, name, type FROM `user` WHERE is_active = 1 AND type = 'api'");
        $stmt2->execute();
        echo "\n  Alle API-User:\n";
        foreach ($stmt2->fetchAll(PDO::FETCH_ASSOC) as $u) {
            echo "    - {$u['user_name']} ({$u['name']}) type={$u['type']}\n";
        }
    }

} catch (Exception $e) {
    echo "FEHLER: " . $e->getMessage() . "\n";
}
