<?php
require __DIR__ . '/../config/bootstrap.php';
require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Database;

$db = Database::getInstance();

function table_exists(PDO $db, string $table): bool {
    try {
        $stmt = $db->prepare("SHOW TABLES LIKE ?");
        $stmt->execute([$table]);
        return (bool)$stmt->fetchColumn();
    } catch (Throwable $e) {
        return false;
    }
}

function columns(PDO $db, string $table): array {
    try {
        $stmt = $db->query("DESCRIBE `$table`");
        return array_map(fn($r) => $r['Field'], $stmt->fetchAll(PDO::FETCH_ASSOC));
    } catch (Throwable $e) {
        return [];
    }
}

function first_existing_col(array $cols, array $candidates): ?string {
    foreach ($candidates as $c) {
        if (in_array($c, $cols, true)) return $c;
    }
    return null;
}

function get_user(PDO $db, string $email): ?array {
    $stmt = $db->prepare("SELECT * FROM users WHERE email=? LIMIT 1");
    $stmt->execute([$email]);
    $u = $stmt->fetch(PDO::FETCH_ASSOC);
    return $u ?: null;
}

function get_roles_for_user(PDO $db, array $user): array {
    $uid = (int)$user['id'];
    $orgId = (int)($user['org_id'] ?? 0);
    $out = [];

    /*
     * Preferred: conference_user_roles / user_conference_roles style tables.
     */
    foreach (['user_conference_roles', 'conference_user_roles', 'conference_users', 'user_roles'] as $table) {
        if (!table_exists($db, $table)) continue;

        $cols = columns($db, $table);
        $userCol = first_existing_col($cols, ['user_id', 'userid', 'uid']);
        $confCol = first_existing_col($cols, ['conference_id', 'conf_id']);
        $roleCol = first_existing_col($cols, ['role_code', 'role', 'role_name', 'code']);
        $roleIdCol = first_existing_col($cols, ['role_id', 'roleid']);

        if (!$userCol) continue;

        try {
            if ($confCol && $roleCol) {
                $sql = "
                    SELECT 
                        t.`$confCol` AS conference_id,
                        t.`$roleCol` AS role_code
                    FROM `$table` t
                    WHERE t.`$userCol`=?
                ";
                $stmt = $db->prepare($sql);
                $stmt->execute([$uid]);
                foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
                    if (!empty($r['conference_id']) && !empty($r['role_code'])) {
                        $out[] = [
                            'conference_id' => (int)$r['conference_id'],
                            'role_code' => (string)$r['role_code'],
                        ];
                    }
                }
            } elseif ($confCol && $roleIdCol && table_exists($db, 'roles')) {
                $sql = "
                    SELECT 
                        t.`$confCol` AS conference_id,
                        r.code AS role_code
                    FROM `$table` t
                    JOIN roles r ON r.id=t.`$roleIdCol`
                    WHERE t.`$userCol`=?
                ";
                $stmt = $db->prepare($sql);
                $stmt->execute([$uid]);
                foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
                    if (!empty($r['conference_id']) && !empty($r['role_code'])) {
                        $out[] = [
                            'conference_id' => (int)$r['conference_id'],
                            'role_code' => (string)$r['role_code'],
                        ];
                    }
                }
            }
        } catch (Throwable $e) {
            echo "WARN reading $table: " . $e->getMessage() . PHP_EOL;
        }
    }

    /*
     * Fallback: current selected/listed conference access from conference_users if role stored differently.
     */
    if (!$out && table_exists($db, 'conference_users')) {
        $cols = columns($db, 'conference_users');
        $userCol = first_existing_col($cols, ['user_id', 'userid']);
        $confCol = first_existing_col($cols, ['conference_id', 'conf_id']);
        $roleCol = first_existing_col($cols, ['role_code', 'role']);

        if ($userCol && $confCol) {
            try {
                $sql = "SELECT `$confCol` AS conference_id" . ($roleCol ? ", `$roleCol` AS role_code" : "") . " FROM conference_users WHERE `$userCol`=?";
                $stmt = $db->prepare($sql);
                $stmt->execute([$uid]);
                foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
                    $out[] = [
                        'conference_id' => (int)$r['conference_id'],
                        'role_code' => (string)($r['role_code'] ?? ($user['role'] ?? $user['role_code'] ?? '')),
                    ];
                }
            } catch (Throwable $e) {}
        }
    }

    /*
     * Final fallback: user's own role + all conferences in same org.
     */
    if (!$out) {
        $role = (string)($user['role_code'] ?? $user['role'] ?? $user['user_role'] ?? '');
        if ($role === '') {
            if (str_contains((string)$user['email'], 'orgadmin')) $role = 'org_admin';
            elseif (str_contains((string)$user['email'], 'chair')) $role = 'conference_chair';
            elseif (str_contains((string)$user['email'], 'organizer')) $role = 'organizer';
            else $role = 'admin';
        }

        try {
            $stmt = $db->prepare("SELECT id AS conference_id FROM conferences WHERE org_id=? ORDER BY id");
            $stmt->execute([$orgId]);
            $confs = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if (!$confs) {
                $confs = $db->query("SELECT id AS conference_id FROM conferences ORDER BY id LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
            }

            foreach ($confs as $c) {
                $out[] = [
                    'conference_id' => (int)$c['conference_id'],
                    'role_code' => $role,
                ];
            }
        } catch (Throwable $e) {}
    }

    /*
     * Deduplicate.
     */
    $dedup = [];
    foreach ($out as $r) {
        if (empty($r['conference_id']) || empty($r['role_code'])) continue;
        $k = $r['conference_id'] . '|' . $r['role_code'];
        $dedup[$k] = $r;
    }

    return array_values($dedup);
}

function conference_row(PDO $db, int $conferenceId): array {
    try {
        $stmt = $db->prepare("SELECT id, org_id, short_name FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([$conferenceId]);
        $c = $stmt->fetch(PDO::FETCH_ASSOC);
        return $c ?: ['id'=>$conferenceId, 'org_id'=>0, 'short_name'=>''];
    } catch (Throwable $e) {
        return ['id'=>$conferenceId, 'org_id'=>0, 'short_name'=>''];
    }
}

$emails = array_slice($argv, 1);
if (!$emails) {
    $emails = [
        'seed.orgadmin@easychair.test',
        'seed.chair@easychair.test',
        'seed.organizer@easychair.test',
        'seed.author@easychair.test',
        'seed.author@easychair.test',
    ];
}

$urls = [
    '/easychair/admin/dashboard',
    '/easychair/admin/branding',
    '/easychair/admin/conference-home',
    '/easychair/admin/committee-images',
    '/easychair/admin/conference-business',
    '/easychair/admin/production',
    '/easychair/admin/certificates',
    '/easychair/admin/email-templates',
    '/easychair/admin/test-email',
    '/easychair/admin/org-smtp',
    '/easychair/admin/conference-role-permissions',
    '/easychair/admin/rbac-scope',
    '/easychair/admin/rbac-matrix',
];

foreach ($emails as $email) {
    echo "\n==============================\n";
    echo $email . "\n";

    $user = get_user($db, $email);
    if (!$user) {
        echo "User not found\n";
        continue;
    }

    $roles = get_roles_for_user($db, $user);

    if (!$roles) {
        echo "No role/conference rows detected.\n";
        continue;
    }

    foreach ($roles as $rr) {
        $conf = conference_row($db, (int)$rr['conference_id']);

        $_SESSION = [];
        $_SESSION['user_id'] = (int)$user['id'];
        $_SESSION['email'] = $email;
        $_SESSION['org_id'] = (int)($conf['org_id'] ?? ($user['org_id'] ?? 0));
        $_SESSION['conference_id'] = (int)$rr['conference_id'];
        $_SESSION['conference_role'] = (string)$rr['role_code'];

        echo "\nConference {$_SESSION['conference_id']} " . ($conf['short_name'] ?? '') . " | role={$_SESSION['conference_role']} | org={$_SESSION['org_id']}\n";

        foreach ($urls as $url) {
            $show = function_exists('ec_can_menu') && ec_can_menu($url) ? 'SHOW' : 'HIDE';

            $row = function_exists('ec_permission_debug_row')
                ? ec_permission_debug_row($url, $_SESSION['conference_role'], $_SESSION['conference_id'], $_SESSION['org_id'])
                : null;

            $extra = '';
            if (is_array($row)) {
                $extra = " row=" . ($row['id'] ?? 'null') .
                    " allowed=" . ($row['is_allowed'] ?? 'null') .
                    " view=" . ($row['can_view'] ?? 'null') .
                    " create=" . ($row['can_create'] ?? 'null') .
                    " update=" . ($row['can_update'] ?? 'null');
            }

            echo str_pad($show, 5) . " " . $url . $extra . PHP_EOL;
        }
    }
}
