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

use App\Core\Database;

$db = Database::getInstance();

$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.reviewer@easychair.test',
        'seed.superadmin@easychair.test',
    ];
}

foreach ($emails as $email) {
    $_SESSION = [];

    $stmt = $db->prepare("SELECT * FROM users WHERE email=? LIMIT 1");
    $stmt->execute([$email]);
    $u = $stmt->fetch(PDO::FETCH_ASSOC);

    echo "\n==============================\n$email\n";

    if (!$u) {
        echo "User not found\n";
        continue;
    }

    $_SESSION['user_id'] = (int)$u['id'];
    $_SESSION['email'] = (string)($u['email'] ?? $email);
    $_SESSION['org_id'] = (int)($u['org_id'] ?? 0);
    $rawRole = (string)($u['role'] ?? $u['role_code'] ?? $u['user_role'] ?? '');
    $resolvedRole = function_exists('ec_scope_normalize_role') ? ec_scope_normalize_role($rawRole, (string)($u['email'] ?? $email)) : $rawRole;
    $_SESSION['role'] = $resolvedRole;
    $_SESSION['user_role'] = $resolvedRole;
    $_SESSION['conference_role'] = $resolvedRole;

    if ($_SESSION['conference_role'] === '') {
        if (str_contains($email, 'super')) $_SESSION['conference_role'] = 'super_admin';
        elseif (str_contains($email, 'orgadmin')) $_SESSION['conference_role'] = 'org_admin';
        elseif (str_contains($email, 'chair')) $_SESSION['conference_role'] = 'conference_chair';
        elseif (str_contains($email, 'organizer')) $_SESSION['conference_role'] = 'organizer';
        elseif (str_contains($email, 'reviewer')) $_SESSION['conference_role'] = 'reviewer';
        elseif (str_contains($email, 'author')) $_SESSION['conference_role'] = 'author';
        $_SESSION['role'] = $_SESSION['conference_role'];
        $_SESSION['user_role'] = $_SESSION['conference_role'];
    }

    ec_scope_auto_select_conference(true);

    echo "role=" . ($_SESSION['conference_role'] ?? '') . PHP_EOL;
    echo "org_id=" . ($_SESSION['org_id'] ?? '') . PHP_EOL;
    echo "conference_id=" . ($_SESSION['conference_id'] ?? 'NONE') . PHP_EOL;
    echo "conference_short_name=" . ($_SESSION['conference_short_name'] ?? '') . PHP_EOL;
    echo "conference_list=" . implode(',', $_SESSION['conference_list'] ?? []) . PHP_EOL;
    echo "landing=" . ec_scope_landing_url() . PHP_EOL;
}
